1

jQueryのmousemove-event は、マウスが移動するたびに発生します。これにより、1 秒あたり数百回のイベントが実行される可能性があります。このコード スニペットがあるとします。

$(document).on('mousemove', function(e){

    /**
    *    This piece of code checks if the mouse is within a 50px range 
    *    on either side of the middle of the page. 
    *    If is, it shows a set of elements (contained in the action_dots variable).
    */

    var treshold = 50;
    var action_dots = $('.branch[open][focus]').children('.branch-line').children('.action-dot');
    var opacity = action_dots.css('opacity');

    if(e.pageX >= ($(window).width()/2 - treshold) && e.pageX <= ($(window).width()/2 + treshold)){
        if(opacity == 0){
            action_dots.transition({ opacity: 1 }, 100);
        }
    }
    else{
        if(opacity == 1){
            action_dots.transition({ opacity: 0 }, 100);
        }
    }
});

イベントが実行されるたびにこれらの変数を宣言するのは効率的ですか? のセレクターに一致するすべての要素を検索するvar action_dots必要があるため、パフォーマンスに負担がかかると考えることができます。または、jQuery はどうにかしてコンテンツをキャッシュできvar action_dotsますか? アクション ドットのopacitycss-property をvar opacity.

4

2 に答える 2