這里粗略記錄一下在項目中輪播圖實現(xiàn)的兩種思路坷随。
首先是內(nèi)容區(qū)域的width和height固定灵再,也就是最常見的情況被廓,通常的做法即是先獲取到內(nèi)容部分每個div或者圖片左邊的距離style.left鲜棠,然后改變每個區(qū)域的style.left(增加或減少特定值畏吓,通常是每個部分的width)來實現(xiàn)輪播的效果。
示例代碼:
function animate(offset) {
//獲取的是style.left图筹,是相對左邊獲取距離帅刀,所以第一張圖后style.left都為負值,
//且style.left獲取的是字符串远剩,需要用parseInt()取整轉(zhuǎn)化為數(shù)字扣溺。
var newLeft = parseInt(list.style.left) + offset;
list.style.left = newLeft + 'px';
//無限滾動判斷
if (newLeft > -958) {
list.style.left = -4790 + 'px';
}
if (newLeft < -4790) {
list.style.left = -958 + 'px';
}
}
prev.onclick = function () {
index -= 1;
if (index < 1) {
index = 5
}
animate(958);
};
next.onclick = function () {
index += 1;
if (index > 5) {
index = 1
}
animate(-958);
};
第二種情況是當內(nèi)容區(qū)域的width和height不固定時,就應該把所有部分(div)看成一個整體瓜晤,然后改變整體的style.left值锥余,height可以根據(jù)瀏覽器的高度來適配,這樣就做到了不同的屏幕分辨率下能自動適配高度痢掠。
示例代碼:
var imgHeight = document.getElementById("bannerlist").getElementsByTagName("img")[0].clientHeight;
document.getElementById("bannerlist").style.height = imgHeight + "px";
function banneranimate(clickIndex) {
document.getElementById("imgs").style.left = -(clickIndex-1)*100+"%";
}
可以看到其實兩種方法的整體思路是一樣的驱犹,不過在實際的運用當中還需要根據(jù)具體情況來改變一些實現(xiàn)的思路。