Help us understand the problem. What is going on with this article?

slideToggleを使ったナビゲーション

More than 3 years have passed since last update.

仕様

よくあるslideToggle(今回はslideUpとslideDown)を利用したナビゲーション。
triggerにhoverした場合にtargetを表示、hoverが外れると非表示。
アニメーション中にイベントが複数回起こった場合は途中で処理を止めて、キューの回数分アニメーションが実行されないようにする。

HTML

イベントのトリガーとなるDOMの子要素にslideToggleさせたいDOMを配置。それぞれデータ属性を付ける。
CSSは適当につければおk。

HTML
<ul>
    <li data-trigger-nav="nav">
        <span>kuma</span>
        <ul data-target-nav="nav">
            <li>kuma</li>
            <li>tama</li>
            <li>kiso</li>
        </ul>
    </li>
        <li>
        <span>akashi</span>
    </li>
    <li data-trigger-nav="nav">
        <span>kongo</span>
        <ul data-target-nav="nav">
            <li>kongo</li>
            <li>hiei</li>
            <li>haruna</li>
            <li>kirishima</li>
        </ul>
    </li>
    <li data-trigger-nav="nav">
        <span>akagi</span>
        <ul data-target-nav="nav">
            <li>akagi</li>
            <li>kaga</li>
        </ul>
    </li>
    <li>
        <span>oyodo</span>
    </li>
</ul>

JS

mouseoverとmouseleaveに分けてイベントを設定。
.stop()でアニメーションの複数回実行を止める。
引数でslideUpとslideDownの速さを設定するように変数定義。

javascript
var Toggle = function(speed){
    var $trigger = $('[data-trigger-nav]');
    var $target = $('[data-target-nav]');
    $trigger.on('mouseover',function(){
        if(!$(this).hasClass('is_Open')) {
            $(this).addClass('is_Open');
            $(this).find($target).stop(true).slideDown(speed);
        }
    });
    $trigger.on('mouseleave',function(){
        if($(this).hasClass('is_Open')) {
            $(this).removeClass('is_Open');
            $(this).find($target).stop(true).slideUp(speed);
        }
    });
};

$(function(){
    Toggle(300);
});

まとめ

泥臭いやり方のような気もしますが、わざわざプラグイン入れるよりはマシなような、そうでもないような。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした