超實用的JavaScript代碼段 Item5 --圖片滑動效果實現

先上圖javascript

這裏寫圖片描述

鼠標滑過那張圖,顯示完整的哪張圖,移除則復位:css

這裏寫圖片描述

簡單的CSS加JS操做DOM實現:html

<!doctype html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>sliding doors</title>
        <link rel="stylesheet" href="styles/reset.css" />
        <link rel="stylesheet" href="styles/slidingdoors.css" />
        <script src="scripts/slidingdoors.js"></script>
    </head>
    <body>
        <div id='container'>
            <img src="images/door1.png" alt="1080P神器" title="1080P神器" />
            <img src="images/door2.png" alt="5.5寸四核" title="5.5寸四核" />
            <img src="images/door3.png" alt="四核5寸" title="四核5寸" />
            <img src="images/door4.png" alt="5.7寸機皇" title="5.7寸機皇" />
        </div>
    </body>
</html>

css:java

#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; }

js操做:markdown

window.onload = function() {
    //容器對象
    var box = document.getElementById('container');

    //得到圖片NodeList對象集合
    var imgs = box.getElementsByTagName('img');

    //單張圖片的寬度
    var imgWidth = imgs[0].offsetWidth;

    //設置掩藏門體露出的寬度
    var exposeWidth = 180;

    //設置容器總寬度
    var boxWidth = imgWidth + (imgs.length - 1) * exposeWidth;
    box.style.width = boxWidth + 'px';

    //設置每道門的初始位置
    function setImgsPos() {
        for (var i = 1, len = imgs.length; i < len; i++) {
            imgs[i].style.left = imgWidth + exposeWidth * (i - 1) + 'px';
        }
    }
    setImgsPos();

    //計算每道門打開時應移動的距離
    var translate = imgWidth - exposeWidth;

    //爲每道門綁定事件
    for (var i = 0, len = imgs.length; 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';
                    //imgs[j].style.left = j*exposeWidth +"px";
                }
            };
            imgs[i].onmouseout = function(){
                setImgPos();
            };
        })(i);
    }
};

版權聲明:本文爲小平果原創文章,轉載請註明:http://blog.csdn.net/i10630226函數

相關文章
相關標籤/搜索