我们的代码如下:
<body>
<div class="blocks">some text here</div>
<div class="end"></div>
</body>
文本可以适合当前浏览器可见部分。
如何检测,该块是否在浏览器窗口的可见部分?
我的意思是,如果资源是1024x768且.block
高度大于768,则.end
是不可见的。
感谢任何帮助。
答案 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)。
计算!它大致应该是:
if((step1 + step3)&gt; step2){ //在这里做点什么 }
请注意,这不会检查您是否滚动过“.end”元素。我没有验证这个,所以希望我不会错过任何重要的东西。
答案 2 :(得分:1)
在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');
}
});