晚上在微博上“拔赤”写了个lazyload插件,发现其中用到一个很有意思的方法”div.inViewportRegion()”,字面意思就是在可视区域内。
在网上找了找,发现这是YUI提供的一个组件,觉得很有意思。
http://gillserver.com/yui/api/dom-region.js.html
如果jQ里面也包含类似的方法,可以做很多事,于是GG了一下,发现国外的同学写过这种选择器,代码表现上更直观。
代码如下:
(function($) {
$.belowthefold = function(element, settings) {
var fold = $(window).height() + $(window).scrollTop();
return fold < = $(element).offset().top - settings.threshold;
};
$.abovethetop = function(element, settings) {
var top = $(window).scrollTop();
return top >= $(element).offset().top + $(element).height() - settings.threshold;
};
$.rightofscreen = function(element, settings) {
var fold = $(window).width() + $(window).scrollLeft();
return fold < = $(element).offset().left - settings.threshold;
};
$.leftofscreen = function(element, settings) {
var left = $(window).scrollLeft();
return left >= $(element).offset().left + $(element).width() - settings.threshold;
};
$.inviewport = function(element, settings) {
return !$.rightofscreen(element, settings) && !$.leftofscreen(element, settings) && !$.belowthefold(element, settings) && !$.abovethetop(element, settings);
};
$.extend($.expr[':'], {
"below-the-fold": function(a, i, m) {
return $.belowthefold(a, {threshold : 0});
},
"above-the-top": function(a, i, m) {
return $.abovethetop(a, {threshold : 0});
},
"left-of-screen": function(a, i, m) {
return $.leftofscreen(a, {threshold : 0});
},
"right-of-screen": function(a, i, m) {
return $.rightofscreen(a, {threshold : 0});
},
"in-viewport": function(a, i, m) {
return $.inviewport(a, {threshold : 0});
}
});
})(jQuery);
来源:http://www.appelsiini.net/projects/viewport
简单测了下,不错,呵呵~
Demo:http://www.zhangjingwei.com/inviewport.zip