HTML的滑動特效可以讓網頁更加美觀和動態,實現起來也比較簡單。以下是一個基本的HTML滑動特效代碼,演示了如何在網頁中添加滑動效果。使用pre標簽包裹代碼,使其更加易讀。
下面是HTML滑動特效的代碼:
<html> <head> <style> #slider{ width:500px; height:300px; overflow:hidden; margin:0 auto; } #slider ul{ width:2000px; list-style:none; margin:0; padding:0; } #slider ul li{ float:left; width:500px; height:300px; } </style> </head> <body> <div id="slider"> <ul> <li><img src="image1.jpg"/></li> <li><img src="image2.jpg"/></li> <li><img src="image3.jpg"/></li> </ul> </div> <script type="text/javascript"> var slider = document.getElementById("slider"); var list = slider.getElementsByTagName("ul")[0]; var buttons = document.getElementById("buttons").getElementsByTagName("span"); var prev = document.getElementById("prev"); var next = document.getElementById("next"); var index = 1; var animated = false; var timer; function animate(offset){ if (offset == 0){ return; } animated = true; var time = 500; var interval = 10; var speed = offset/(time/interval); var left = parseInt(list.style.left) + offset; var go = function (){ if ((speed >0 && parseInt(list.style.left)< left) || (speed< 0 && parseInt(list.style.left) >left)){ list.style.left = parseInt(list.style.left) + speed + "px"; setTimeout(go, interval); } else { list.style.left = left + "px"; if (left >-500){ list.style.left = -1500 + "px"; } if (left< -1500){ list.style.left = -500 + "px"; } animated = false; } }; go(); } function play(){ timer = setInterval(function (){ next.onclick(); }, 2000); } function stop(){ clearInterval(timer); } function showButton(){ for (var i = 0; i< buttons.length ; i++){ if (buttons[i].className == "on"){ buttons[i].className = ""; break; } } buttons[index - 1].className = "on"; } prev.onclick = function (){ if (animated){ return; } if (index == 1){ index = 3; } else { index -= 1; } showButton(); animate(500); }; next.onclick = function(){ if (animated){ return; } if (index == 3){ index = 1; } else { index += 1; } showButton(); animate(-500); }; for (var i = 0; i< buttons.length; i++) { buttons[i].onclick = function () { if (animated) { return; } if (this.className == 'on') { return; } var myIndex = parseInt(this.getAttribute('index')); var offset = -500 * (myIndex - index); index = myIndex; showButton(); animate(offset); }; } slider.onmouseover = stop; slider.onmouseout = play; play(); </script> </body> </html>
這個代碼實現了一個簡單的3張圖片的輪播效果。通過 jQuery 可以實現更加豐富的滑動效果。