滑动门的例子:
HTML:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>sliding doors</title> <link rel="stylesheet" href="styles/slidingdoors.css"/> </head> <body> <div id="container"> <img src="images/door1.jpg" alt="door1" title="door1"/> <img src="images/door2.webp" alt="door2" title="door2"/> <img src="images/door3.jpg" alt="door3" title="door3"/> <img src="images/door4.jpg" alt="door4" title="door4"/> </div> <script src="scripts/slidingdoors.js"></script> </body> </html>
JavaScript:
window.onload = function(){//页面加载完毕。页面请求的所有资源加载完毕 //容器对象 var box = document.getElementById("container"); //获得图片nodelist对象集合 var imgs = box.getElementsByTagName("img"); //单张图片的宽度 var imgWidth = imgs[0].offsetWidth//属于DOM样式的内容 //设置掩藏门体露出的宽度 var exposeWidth = 160; //设置容器总宽度 var boxWidth = imgWidth + (imgs.length - 1) * exposeWidth; box.style.width = boxWidth + "px";//style是DOM中css属性设置的内容 //设置每道门的初始位置 function setImgsPos(){ for(var i = 1; i < imgs.length; i++){ imgs[i].style.left = imgWidth + (i - 1) * exposeWidth + "px";// } } setImgsPos(); var translate = imgWidth - exposeWidth; for(var i = 1; i < imgs.length; i++) { //使用立即调用函数表达式,为了获得不同的i值 (function(i){ imgs[i].onmouseover = function(){ //this.left = 0 + "px"; //先将每道门复位 setImgsPos(); for(var j = 0; j <= i; j++){ imgs[j].style.left = parseInt(imgs[j].style.left, 10) - translate + "px"; } } })(i) } }
css:
#container{ height:280px; margin: 0 auto; border-right:1px solid #ccc; border-bottom:1px solid #ccc; overflow: hidden; position: relative; } #container img{ position: absolute; display: block; left:0; border-left: 1px solid #ccc; }