LoginSignup
2
2

More than 5 years have passed since last update.

よく使う汎用jQuery::ホバーボタン

Last updated at Posted at 2013-01-31
test.html
<img src="/img/off/hoge.gif">
<!-- 下記ボタンは動作しない -->
<img src="/img/off/hage.gif" class="not_hover">
common.js
    //  /img/off/と/img/on/にある同一ファイル名の画像を切り替える
    $("img:not(.not_hover), input[type='image']:not(.not_hover)")
        .on('mouseenter touchstart', function() {
            $(this).attr("src", $(this).attr("src").replace('/off/', '/on/'));
        })
        .on('mouseleave touchend', function() {
            $(this).attr("src", $(this).attr("src").replace('/on/', '/off/'));
        })
    ;
    //  CSS対応
    $(".bg-hover:not(.not_hover)")
        .on('mouseenter touchstart', function() {
            $(this).css("background-image", $(this).css("background-image").replace('/off/', '/on/'));
        })
        .on('mouseleave touchend', function() {
            $(this).css("background-image", $(this).css("background-image").replace('/on/', '/off/'));
        })
    ;

画像はファイル名を同じにしてonフォルダとoffフォルダへ。
動作させたくない場合はclass="not_hover"
何となくずっと使ってるけど、セレクタをclass指定にした方が軽いかも。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2