@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;
}
参数作为对象文字“map”的属性传递,覆盖构造函数中的硬编码默认值。对于未包含的任何参数,将使用默认值。这里有几个例子:
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();
笔记:
- 工作演示在这里。
- 依赖:jQuery 1.0 或更高版本
.reset()
自动调用.stop()
,因此无需.stop()
事先调用。
- 没有规定在实例化后更改设置,但稍加考虑就可以做到这一点。
- jQuery 插件将是类似的,但会花费更多时间来开发(几乎没有优势)。