【问题标题】:Check block visibility检查块可见性
【发布时间】:2011-03-22 15:04:32
【问题描述】:

我们有如下代码:

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

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

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

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

  • 我们应该在 window.ready 和浏览器窗口更改时检测到这一点。
  • 如果块可见,则运行一些函数。

感谢任何帮助。

【问题讨论】:

  • 您是否需要检测整个元素是否在视图中或仅在顶部或底部?

标签: javascript jquery html css window


【解决方案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');
    }   
});

【讨论】:

  • 这不适用于滚动(即使我们添加了滚动检查)。您只关心元素宽度,而实际上您必须考虑左偏移和上偏移值。
  • 谢谢,干得好。我的版本 > jsfiddle.net/hPjbh 虽然你的版本更有条理。
【解决方案2】:

先抓取窗口尺寸。

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

接下来抓取 div 相对于文档的位置:

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

然后做你的如果:

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

您可能还想获取 div 尺寸,以防它可能超出顶部或左侧的范围。

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

编辑:添加了 scrollTop 以考虑滚动。

【讨论】:

    【解决方案3】:

    作为一个快速的答案,您必须在加载时进行一些计算(psuedocode 假定为 jQuery)。

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

      如果((第 1 步 + 第 3 步)> 第 2 步){ //在这里做事 }

    请注意,这不会检查您是否滚动过“.end”元素。我没有验证这个,所以希望我不会错过什么大事。

    【讨论】:

      【解决方案4】:
      1. 获取元素的offsetTop和offsetLeft属性
      2. 获取相关元素的宽度
      3. 获取屏幕宽度
      4. 做相关的数学运算,看看元素是在视口中还是现在。

      在 jQuery 中你可以做类似的事情

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

      编辑: 简单有效:http://jsfiddle.net/hPjbh/

      【讨论】:

      • 好答案。另外,你可以$("#element").offset().top
      猜你喜欢
      • 1970-01-01
      • 2011-06-02
      • 2017-02-28
      • 2012-09-18
      • 2012-01-26
      • 2013-06-28
      • 2011-02-28
      • 2014-08-06
      相关资源
      最近更新 更多