<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title>slideDoor</title>
<link type="text/css" rel="stylesheet" href="../common/reset.css" />
<link type="text/css" rel="stylesheet" href="css/slideDoor.css" />
</head> <body>
<div id='container'>
<img src="img/door1.png" alt="1080P神器" title="1080P神器" />
<img src="img/door2.png" alt="5.5寸四核" title="5.5寸四核" />
<img src="img/door3.png" alt="四核5寸" title="四核5寸" />
<img src="img/door4.png" alt="5.7寸机皇" title="5.7寸机皇" />
</div>
</body>
<script type="text/javascript" src="js/slideDoor.js"></script> </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); } }