@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