jQuery 事件 scroll() 方法的使用教程

作者:袖梨 2022-06-25

首先介绍一下(document).height()与$(window).height()的区别:

$(document).height() 是获取整个页面的高度
$(window).height() 是获取当前 也就是你浏览器所能看到的页面的那部分的高度 这个大小在你缩放浏览器窗口大小时 会改变 与document是不一样的

scrollTop()和scrollLeft()的使用:

$(document).scrollTop() 获取垂直滚动的距离 即当前滚动的地方的窗口顶端到整个页面顶端的距离
$(document).scrollLeft() 这是获取水平滚动条的距离

要获取顶端 只需要获取到scrollTop()==0的时候 就是顶端了

要获取底端 只要获取scrollTop()>=$(document).height()-$(window).height() 就可以知道已经滚动到底端了

下面介绍一个scroll事件实现监控滚动条分页简单示例,使用ajax加载:

代码如下 复制代码
$(document).ready(function () {
$(window).scroll(function () {
//$(window).scrollTop()这个方法是当前滚动条滚动的距离
//$(window).height()获取当前窗体的高度
//$(document).height()获取当前文档的高度
var bot = 50; //bot是底部距离的高度
if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
//当底部基本距离+滚动的高度〉=文档的高度-窗体的高度时;
//我们需要去异步加载数据了
$.getJSON("url", { page: "2" }, function (str) { alert(str); });
}
});
});

例子

去掉窗口滚动条(CSS中加入):

代码如下 复制代码

body {
overflow-x:hidden;
}

去掉窗口滚动条之后,拖动表格控件滚动条到最右仍然不能看到完整表格。
解决:

监听控件的scroll方法,当列实际宽度超出窗口宽度时,横向滚动窗口,以便查看整个表格

代码如下 复制代码
XXX.scroll(function (e) {
XXX.scrollLeft($(this).scrollLeft());
if (totalWidth > $(window).width()){
$(window).scrollLeft($(this).scrollLeft());
}
})


用jquery的话,这个事件scroll 可以查看jquery api :http://api.j**que*ry.com/scroll/

但scroll 事件有一个缺陷,就是只能判断滚动条滚动,而不能监控滚动条停止滚动时的事件。

现用jquery扩展一下scroll 事件,新增

不多说,直接上代码实在点。

代码如下 复制代码
(function(){

var special = jQuery.event.special,
uid1 = 'D' + (+new Date()),
uid2 = 'D' + (+new Date() + 1);

special.scrollstart = {
setup: function() {

var timer,
handler = function(evt) {

var _self = this,
_args = arguments;

if (timer) {
clearTimeout(timer);
} else {
evt.type = 'scrollstart';
jQuery.event.handle.apply(_self, _args);
}

timer = setTimeout( function(){
timer = null;
}, special.scrollstop.latency);

};

jQuery(this).bind('scroll', handler).data(uid1, handler);

},
teardown: function(){
jQuery(this).unbind( 'scroll', jQuery(this).data(uid1) );
}
};

special.scrollstop = {
latency: 300,
setup: function() {

var timer,
handler = function(evt) {

var _self = this,
_args = arguments;

if (timer) {
clearTimeout(timer);
}

timer = setTimeout( function(){

timer = null;
evt.type = 'scrollstop';
jQuery.event.handle.apply(_self, _args);

}, special.scrollstop.latency);

};

jQuery(this).bind('scroll', handler).data(uid2, handler);

},
teardown: function() {
jQuery(this).unbind( 'scroll', jQuery(this).data(uid2) );
}
};

})();

可以将上面代码保存到一个文件,这相当于一个插件,呵呵。调用方法如下:

代码如下 复制代码
(function(){
jQuery(window).bind('scrollstart', function(){
console.log("start");
});

jQuery(window).bind('scrollstop', function(e){
console.log("end");
});

})();

相关文章

精彩推荐