1

jQuery 中的mousemove-event 会在每次鼠标移动时触发,这会导致每秒执行数百次事件。假设我们有这个代码片段。

$(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

2

就效率而言,不,为鼠标移动的每个像素运行该代码并不是很有效。您可以做的是在鼠标停止移动x几毫秒后运行该代码。像这样的东西:

var mouseTimer;
$(document).on('mousemove', function(e) {
    clearTimeout(mouseTimer);
    mouseTimer = setTimeout(function() {    
        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);
            }
        }
    }, 50); // runs 50ms after mouse movement stops.
});
于 2013-10-25T13:09:23.237 回答
0

根据我的评论:如果没有动态添加点,您只需在$(document).on调用之外声明 action_dots ,以便在页面准备就绪时填充一次。

$(function(){ // JQuery ready - modern version

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

    $(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 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);
            }
        }
    });
});

该 JQuery 选择器是代码中最慢的部分,但可能只需要运行一次(或者每次将新项目添加到页面时至少只运行一次 - 如果它是动态的)。

如果您想要一个特定的示例,请发布整个 JS(以防您缺少 JQuery“准备好的包装器” - 未显示)。

于 2013-10-25T13:15:02.180 回答