jQuery插件实现无缝滚动特效

2020-05-29 07:11:58易采站长站整理

if (ul_w <= root.width())
clearInterval(t);
else
marquee();
}
}
else {
       var li_h = li_first.outerHeight(true); //单个li标签的高度
       var ul_h = li_h * li_num; //ul标签的高度

_ul.css({ height: ul_h }); //设置ul高度

marquee = function () {
_ul.animate({ marginTop: "-=1" }, 0, function () {
var _mtop = Math.abs(parseInt($(this).css("margin-top"))); //取绝对值
if (_mtop > li_h) {
$("> li:first", $(this)).appendTo($(this));
$(this).css("margin-top", 0);
}
});
};
//ul长度小于box长度时则不滚动,反之滚动
isRoll = function (t) {
if (ul_h <= root.height())
clearInterval(t);
else
marquee();
}
}

//遵循链式原则,并进行初始化
return root.each(function (i) {
//超出内容隐藏,防止用户没写overflow样式
$(this).css({ overflow: "hidden" });

timer[i] = setInterval(function () {
isRoll(timer[i]);
}, settings.speed);

//鼠标进入停止滚动,离开继续滚动
$(this).hover(function () {
clearInterval(timer[i]);
}, function () {
timer[i] = setInterval(function () {
isRoll(timer[i]);
}, settings.speed);
});

});

};
})(jQuery);

基本的代码说明注释写的很清楚了,下面对个别知识点作下讲解:

1) 、var timer=[];  之前timer并不是声明为数组类型的,是在我写demo的时候,由于页面同时存在两个无缝滚动的应用(为了演示横向和纵向), 出现了bug。

因为他们两个共用了一个timer计时器,当鼠标进入其中一个时,另一个的timer也被clear了。之后修改代码将其声明为数组对象,再通过root.each()就实现了每个插件应用都有自己独立的timer计时器,互不干扰。也就是说此插件支持页面同时存在多个无缝滚动应用。

2) 、outerWidth() /outerHeight()函数。 这个函数比较强大,它获取的不仅仅是元素的宽度/高度,实际上 outerWidth()=width+borderLeft+borderRight+marginLeft+marinRight;当它设置为true后,即:outerWidth(true),它也会将padding计算进来:outerWidth()=width+borderLeft+borderRight+marginLeft+marinRight+paddingLeft+paddingRight;

下面给出DEMO代码:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
*{ margin:0; padding:0;}
ul,ul li{ list-style:none;}
.wrap{ width:1000px; margin:50px auto;}
.box1,.box2,.box3{ overflow:hidden; float:left;border:1px solid gray;}