如何提醒var distance_all(来自var distance_top + distance_bottom)?

时间:2014-10-09 12:31:18

标签: javascript jquery

如何提醒var distance_all(来自var distance_top + distance_bottom)?

当鼠标位置topbottom小于100像素时。它会提醒distance_all(来自var distance_top + distance_bottom)。

但不行,我该怎么做?

http://jsfiddle.net/dyjb8r9w/1/

<script>

$(window).load(function(){


(function() {

    var mY, distance_top,
        $distance_top = $('#distance_top span'),
        $element_top  = $('#element_top');

    function calculatedistance_top(elem , mouseY) {
        return Math.floor(Math.sqrt(Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2)));
    }

    $(document).mousemove(function(e) {        
        mY = e.pageY;
        distance_top = calculatedistance_top($element_top , mY);
        $distance_top.text(distance_top);

        if (distance_top < 100) 
        { distance_all = distance_bottom + distance_top;
          alert(distance_all);}  
    });
})();




(function() {

    var mY, distance_bottom,
        $distance_bottom = $('#distance_bottom span'),
        $element_bottom  = $('#element_bottom');

    function calculatedistance_bottom(elem , mouseY) {
        return Math.floor(Math.sqrt(Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2)));
    }

    $(document).mousemove(function(e) {        
        mY = e.pageY;
        distance_bottom = calculatedistance_bottom($element_bottom , mY);
        $distance_bottom.text(distance_bottom);  

        if (distance_bottom < 100) 
        { distance_all = distance_bottom + distance_top;
          alert(distance_all);}  

    });
})();

});
</script>

1 个答案:

答案 0 :(得分:1)

distance_bottom在第一个mousemove事件处理程序中没有值。将代码拆分为两个独立的mousemove事件处理程序,其中包含大量重复代码,这根本不是一个好主意。

重写<script>代码:

Fiddle

$(document).ready(function()
{     
    var $distance_top = $('#distance_top span');
    var $element_top  = $('#element_top');
    var $distance_bottom = $('#distance_bottom span');
    var $element_bottom  = $('#element_bottom');

    function calculateDistance(elem, mouseY)
    {
        return Math.floor(Math.abs(mouseY - (elem.offset().top + elem.height() / 2)));
    }

    $(document).mousemove(function(e)
    {        
        var mY = e.pageY;
        var distance_top = calculateDistance($element_top, mY);
        var distance_bottom = calculateDistance($element_bottom, mY);
        $distance_top.text(distance_top);
        $distance_bottom.text(distance_bottom);
        if (distance_top < 100) 
        {
            var distance_all = distance_bottom + distance_top;
            alert(distance_all);
        }  
    });
});