检查块可见性

时间:2011-03-22 15:04:33

标签: javascript jquery html css window

我们的代码如下:

<body>
<div class="blocks">some text here</div>
<div class="end"></div>
</body>

文本可以适合当前浏览器可见部分。

如何检测,该块是否在浏览器窗口的可见部分?

我的意思是,如果资源是1024x768且.block高度大于768,则.end是不可见的。

  • 我们应该在window.ready以及浏览器窗口更改中检测到这一点。
  • 如果块可见,则运行一些功能。

感谢任何帮助。

4 个答案:

答案 0 :(得分:1)

首先抓住窗口尺寸。

var windowSize = {width: $(window).width(), height: $(window).height() + $(window).scrollTop()};

接下来抓住与文档相关的div位置:

var position = $('.block').offset()

然后制作你的if:

if(position.top > windowSize.height){ /* here we go */ }

您可能还想抓住div尺寸,以防有可能在顶部或左侧超出范围。

你可以将它变成一个返回布尔值的函数,然后在window.resize和document.ready事件上调用它。

编辑:添加了scrollTop以便进行滚动。

答案 1 :(得分:1)

作为一个快速回答,你必须对加载进行一些计算(psuedocode假定jQuery)。

  1. 找到窗口高度$(窗口).outerHeight(true)
  2. 找到“.end”元素的偏移量$(“。end”)。offset()
  3. 找到窗口的滚动距离$(窗口).scrollTop()
  4. 计算!它大致应该是:

    if((step1 + step3)&gt; step2){     //在这里做点什么 }

  5. 请注意,这不会检查您是否滚动过“.end”元素。我没有验证这个,所以希望我不会错过任何重要的东西。

答案 2 :(得分:1)

  1. 获取元素的offsetTop和offsetLeft属性
  2. 获取有问题的元素的宽度
  3. 获取屏幕宽度
  4. 执行相关数学运算并查看元素是否在视口中或现在。
  5. 在jQuery中你可以做类似

    的事情

    $("#element").attr("offsetTop")

    修改 简单有效:http://jsfiddle.net/hPjbh/

答案 3 :(得分:1)

某事like this

$.fn.viewport = (function() {
    var vp = function(el, opts){
        this.el = $(el);
        this.opts = opts;
        this.bind();    // bind resize and scroll
        this.change();  // init change
    };
    vp.prototype = {
        bind: function(){
            $(window).bind('resize scroll', 
                           $.proxy(this.change, this));
        },
        change: function(e){
            var p = this.el.position(),
                o = this.el.offset(),
                d = { w: this.el.width() +o.left, h: this.el.height()+o.top },
                win = $(window),
                winD = {w:win.width() + win.scrollLeft(), h:win.height()+win.scrollTop()};

            if(d.w <= winD.w && d.h <= winD.h){
                console.log('inview');   
            } else {
                console.log('out of view');
                this.opts.outOfView.call(this);
            }
        }
    };
    return function(opts){
        return $(this).each(function(){
           $(this).data('vp', new vp(this, opts)); 
        });
    };
})();

并像这样使用:

$('#el').viewport({
    outOfView: function(){
        alert('out of view');
    }   
});