マウスオーバーで画像内にキャプションを表示し、マウスアウトでキャプションを非表示する動作のサンプルです。jQueryのhoverメソッドを利用しています。キャプションの表示位置は自動計算のため、複数行のキャプションにも対応しています。
htmlのコードは下記になります。
画像とキャプションを格納するdivタグにclass=”hover_image″を付与します。
<p class="hover_title">マウスオーバーデモ</p>
<div class="hover_image_wrap col04">
<div class="hover_image">
<a href="#">
<img src="hover01.jpg" alt="">
<p class="caption_txt">キャプション01</p>
</a>
</div>
<div class="hover_image">
<a href="#">
<img src="hover02.jpg" alt="">
<p class="caption_txt">キャプション02</p>
</a>
</div>
<div class="hover_image">
<a href="#">
<img src="hover03.jpg" alt="">
<p class="caption_txt">キャプション03</p>
</a>
</div>
<div class="hover_image">
<a href="#">
<img src="hover04.jpg" alt="">
<p class="caption_txt">キャプション04</p>
</a>
</div>
</div>
続いてCSSのコードです。
画像とキャプションを格納したclass=”hover_image”のdivタグはFlexboxで横並びにしています。
キャプションのpタグはpositionでtop: 100%;の位置に配置し、class=”hover_image”のdivタグにoverflow: hidden;を設定することで非表示にします。また、キャプションのpタグはスムーズな動作になるよう、transition: 0.5s;を設定しておきます。
.hover_image_wrap {
display: flex;
margin: 0 0 3em;
}
.col04 .hover_image {
width: 24%;
}
.hover_image {
position: relative;
margin: 0 8px 0 0;
overflow: hidden;
}
.hover_image:last-child {
margin: 0;
}
.hover_image a {
display: block;
}
.caption_txt {
position: absolute;
top: 100%;
left: 0;
width: 100%;
margin: 0;
padding: 8px 0;
line-height: 1.4;
background: #000000;
color: #ffffff;
text-align: center;
transition: 0.5s;
}
@media screen and (max-width: 640px) {
.hover_image_wrap {
flex-wrap: wrap;
}
.col04 .hover_image {
width: 100%;
}
.hover_image {
margin: 0 0 10px 0;
}
}
最後にjQueryのコードです。
hoverメソッドでマウスオーバーとマウスアウトの処理を分けて記述します。
マウスオーバー時はキャプションのpタグにCSSを追加します。リンク領域のaタグの高さからキャプションのpタグの高さを差し引いて、topの位置を決めます。高さはinnerHeightを利用して調べます。
マウスアウト時はremoveAttrでキャプションのpタグに追加したstyle属性を削除します。
$(function() {
$('.hover_image a').hover(
function(){
var caption = $(this).children('.caption_txt');
caption.css('top', $(this).innerHeight() - caption.innerHeight());
},
function(){
var caption = $(this).children('.caption_txt');
caption.removeAttr('style');
}
);
});