ホバーエフェクトってなに
「マウスオーバー」や「マウスアウト」時の効果で動きのある表現の基本
ボタンのホバーエフェクト
例①
$(funtion(){
var duration = 300
$('#buttons1 button:nth-child(-n+4)')
.on('mouseover', function() { ←第二引数は無名関数
$(this).stop(true).animate({ ←stop(true)で要素のanimateを停止できる
backgroundColor: '#ae5e9b',
color: '#fff'
}, duration); ←変数durationには数値の300が入っている。animateが適用されるまでの時間。
})
.on('mouseout', function(){
$(this).stop(true).animate({
backgroundColor: '#fff',
color: '#ebc000'
}, duration);
});
ボタンのホバーエフェクト
例②
$(funtion(){
var duration = 300
$('#buttons1 button:nth-child(n+5):nth-child(-n+8)')
.on('mouseover', function(){
$(this).stop(true).animate({
borderWidth: '12px', ←ここポイント。ボタンのanimateが独特
color: '#ae5e9b'
}, duration, 'easeOutSine'); ←'easeOutSine’はイージングの種類。アニメーションが即座に実行される。
})
.on('mouseout', function(){
$(this).stop(true).animate({
borderWidth: '0px',
color: '#ebc000'
}, duration, 'easeOutSine');
});
ボタンのホバーエフェクト
例③
・マウスオーバーすると、色面が左側からスライドインして、背景色と文字色の異なるボタンに変化する。
・マウスアウトすると元に戻る。
$(funtion(){
var duration = 300
$('#buttons1 button:nth-child(n+9)')
.on('mouseover', function(){
$(this).find('> span') ←findメソッドでspanタグを指定(buttons1 button:nth-child(n+9)からspanタグへ)。
.stop(true).animate({
width: '100%' ←ボタンが100%にかぶせる
}, duration, 'easeOutQuad'); ←animateが実行される速度
})
.on('mouseout', function(){
$(this).find('> span')
.stop(true).animate({width: '0%'}, duration, 'easeOutQuad');
});
});
#buttons1 button {
position: relative;
}
#buttons1 button .bg {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
overflow: hidden; ←こいつ
}
#buttons1 button span span {
display: block;
width: 224px;
height: 80px;
line-height: 80px;
color: #fff; ←重ねたボタンに異なる色の指定
background-color: #ae5e9b; ←重ねたボタンに異なる色の指定
border-radius: 20px;
}
・jsでは overflow: hidden;が指定された要素の幅をアニメーションさせることで、今回作成する効果を実現します。
・find()メソッドはjQueryオブジェクトに含まれる各要素の子孫要素の中から、セレクタを使用してさらに要素を絞り込むメソッドです 。今回はfind()メソッドの引数にspan要素を指定することで、処理対象を重ねた方のボタン(span要素内のボタン)に限定しています。
find('絞り込むセレクタ')
このようにon()メソッドの処理対象と、animate()メソッドの処理対象を変更することで、横にスライドしていく色面のアニメーションを実現しています。