@andy,这是Tom Th的想法,即一个js构造函数,从中可以实例化多个实例:
function bgScroller(options) {
var settings = {
containerID: '', //id of the scroller's containing element
scrollSpeed: 50, //Speed in milliseconds
step: 1, //How many pixels to move per step
imageHeight: 0, //Background image height
headerHeight: 0, //How tall the header is.
autoStart: true
};
if(options) {
jQuery.extend(settings, options);
}
var current = 0, // The current pixel row
restartPosition = -(settings.imageHeight - settings.headerHeight), //The pixel row where to start a new loop
interval = null,
$container = jQuery('#' + settings.containerID),
that = {};
if(!$container.length || !settings.imageHeight || !settings.headerHeight) {
return false; //nothing will work without these settings so let's not even try
}
function setBg() {
$container.css("background-position", "0 " + current + "px");
}
function scrollBg(){
current -= settings.step;//Go to next pixel row.
//If at the end of the image, then go to the top.
if (current <= restartPosition){
current = 0;
}
setBg();
}
that.reset = function() {
that.stop();
current = 0;
setBg();
}
that.start = function() {
interval = setInterval(scrollBg, settings.scrollSpeed);
};
that.stop = function(){
clearInterval(interval);
};
that.reset();
if(settings.autoStart) {
that.start();
}
return that;
}
参数如文字“地图”,覆盖在构造函数中的硬编码默认值对象的属性传递。对于不包含的任何参数,将使用默认值。这里有几个例子:
var headerScroller = new bgScroller({
containerID: "header",
scrollSpeed: 70, //Speed in milliseconds
imageHeight: 4300, //Background image height
headerHeight: 300, //How tall the header is.
});
var otherScroller = new bgScroller({
containerID: "myOtherDiv",
scrollSpeed: 30, //Speed in milliseconds
imageHeight: 2800, //Background image height
headerHeight: 200, //How tall the header is.
});
我已经包含了三种公共方法; .reset()
,.start()
和.stop()
,其在实例化之后提供对滚动器的有限控制。使用方法如下:
headerScroller.stop();
headerScroller.reset();
headerScroller.start();
注:
- 工作演示here。
- 依赖关系:jQuery的1.0或更高版本
.reset()
电话.stop()
自动所以没有必要调用.stop()
提前。
- 没有规定在实例化之后更改设置,但这可能需要多一点思考。
- jQuery插件会很相似,但需要一点时间来开发(几乎没有优势)。
你可以创建一个插件......我建议你看看jQuery网站上的插件创作指南。 – elclanrs
为什么不把所有上述内容都归入它自己的对象中,那么你可以简单地实例化多个实例,传递滚动速度,div标签等? –
老实说,编写一个插件是有点超越我,我真的刚刚开始使用jQuery。 – andy