代码之家  ›  专栏  ›  技术社区  ›  superUntitled

jquery:当一个DIV在浏览器窗口中可见时的通知

  •  2
  • superUntitled  · 技术社区  · 16 年前

    我有一个脚本,每当浏览器窗口中有一个给定的DIV时,它就会通知控制台日志,这并不漂亮,但这里是:

    $(window).bind('scroll', function(){
       var $canvas = $('div#example');
       var pos     = $canvas.offset();
       var total = pos.top + $($canvas).height();
       var wndtop  = $(this).scrollTop();
    
       if(wndtop <= pos || wndtop >= total ){ 
           console.log("off screen")
       }
        if(wndtop >= pos || wndtop <= total ){ 
           console.log("on screen")
       }
    
    });
    

    如果DIV在页面顶部,则此脚本可以正常工作,但如果它不在页面顶部,则它将始终返回“在屏幕上”。我如何修改这个,以便它返回正确的信息,无论DIV在页面上的什么位置?

    1 回复  |  直到 16 年前
        1
  •  1
  •   Chase Wilson    16 年前

    http://www.jsfiddle.net/Q7T3b/

    我想这是个很酷的小练习。
    通常我会使用某种方法扩展本机编号对象,比如withinrange(低、高);

    但这似乎奏效了…虽然它在任何情况下都无法超越“看起来足够好”;但它很脏。所以不要告诉任何人我做了这件事。

    var canvas = $('#other');  
    var win = $(window);  
    
    win.bind('scroll', function(){
       var pos = canvas.offset();
       var total = pos.top + canvas.height() + win.height();
       win.top  = win.scrollTop();
       var d = win.height() + win.top;
    
       if( pos.top < d && !(total < d) ){ 
           console.log("on screen")
       }
    });​
    

    当您在诸如“滚动”或“鼠标移动”之类的密集事件上运行功能时,您需要确保在其中运行的内容尽可能灵活。dom查询除了速度快之外,还有很大的开销。我建议避免对此类事件提出疑问。