寫了一個slideDoor,reset.css就不放上來了,自行添加吧! 1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>slideDoor</title> 7 <link type="text/css"
寫了一個slideDoor,reset.css就不放上來了,自行添加吧!
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>slideDoor</title> 7 <link type="text/css" rel="stylesheet" href="../common/reset.css" /> 8 <link type="text/css" rel="stylesheet" href="css/slideDoor.css" /> 9 </head> 10 11 <body> 12 <div id='container'> 13 <img src="img/door1.png" alt="1080P神器" title="1080P神器" /> 14 <img src="img/door2.png" alt="5.5寸四核" title="5.5寸四核" /> 15 <img src="img/door3.png" alt="四核5寸" title="四核5寸" /> 16 <img src="img/door4.png" alt="5.7寸機皇" title="5.7寸機皇" /> 17 </div> 18 </body> 19 <script type="text/javascript" src="js/slideDoor.js"></script> 20 21 </html>
#container { height: 477px; 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; }
window.onload = function() { // 容器對象 var box = document.getElementById('container'); // 獲得圖片的集合 var imgs = box.getElementsByTagName('img'); var len = imgs.length; // 單張圖片的寬度 var imgWidth = imgs[0].offsetWidth; // 圖片露出的寬度 var exposeWidth = 160; // 設置容器的總寬度 var boxWidth = imgWidth + (len - 1) * exposeWidth; // 每個door 滑動的距離 var translate = imgWidth - exposeWidth; box.style.width = boxWidth + 'px'; // 設置door 的初始位置 function setImgsPos() { for (var i = 1; i < len; i++) { imgs[i].style.left = imgWidth + exposeWidth * (i - 1) + "px"; } } setImgsPos(); // 為door 綁定事件 for (var i = 0; i < len; i++) { // 立即調用的函數表達式,為了獲得不同的i值 (function(i) { imgs[i].onmouseover = function() { // 先將每道門複位 setImgsPos(); // 打開門 for (var j = 1; j <= i; j++) { imgs[j].style.left = parseInt(imgs[j].style.left, 10) - translate + 'px'; } } })(i); } }