1. 程式人生 > 其它 >前端學習-第二階段-day06

前端學習-第二階段-day06

技術標籤:前端學習日記

練習目標

輪播圖,滑鼠移入輪播停止,移出繼續輪播,點選小圓點自動跳轉相應圖片
在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title
>
<style> * { padding: 0; margin: 0; list-style: none; } .box { width: 600px; height: 400px; margin: 50px auto; border: 2px solid teal; position: relative; overflow
: hidden; } .box ul { width: 2400px; position: absolute; left: 0px; } .box li { float: left; } .box p { position: absolute; bottom: 10px; width: 100%; text-align
: center; } .box p span { display: inline-block; width: 15px; height: 15px; background: #000; border-radius: 50%; margin-right: 5px; } .box p .active { background: teal; }
</style> </head> <body> <div class="box"> <ul> <li><img src="./image/t1.png" alt=""></li> <li><img src="./image/t2.png" alt=""></li> <li><img src="./image/t3.png" alt=""></li> <li><img src="./image/t4.png" alt=""></li> </ul> <p><span class='active'></span><span></span><span></span><span></span></p> </div> <script src="./js/myPackage.js"></script> <script> var oSpan = document.getElementsByTagName("span"); var oBox = document.getElementsByTagName("div")[0]; var oUl = oBox.getElementsByTagName("ul")[0]; var n = 0; var over = setInterval(auto, 1000); function auto() { n++; if (-600 * n == -2400) { n = -1; } running(oUl, "left", 30, -600 * n); for (i = 0; i < oSpan.length; i++) { oSpan[i].className = ""; } oSpan[n].className = "active"; } oUl.onmouseover = function () { clearInterval(over); } oUl.onmouseout = function () { clearInterval(over); over = setInterval(auto, 1000); } for (b = 0; b < oSpan.length; b++) { oSpan[b].index = b; oSpan[b].onclick = function () { clearInterval(over); oUl.style.left = (this.index) * (-600) + "px"; for (i = 0; i < oSpan.length; i++) { oSpan[i].className = ""; } this.className = "active"; over = setInterval(auto, 1000); } } </script> </body> </html>

js程式碼

/* 
*作用:獲取元素的樣式
*@parm {object} elem:標籤
*@parm {string} attr:屬性
*/
function getStyle(elem,arr){//標籤:elem  屬性:attribute
    if(window.getComputedStyle){
        //標準
        var value= getComputedStyle(elem)[arr];
    }else{
        //IE
        var value=elem.currentStyle[arr];
    }
    return value
}

/* 
*作用:運動元素
*@parm {object} elem:標籤
*@parm {string} attr:屬性
*@parm {number} step:步長
*@parm {number} target:目標值
*/
function running(elem, attr, step, target) { //運動元素elem,屬性attr,步長step,目標值target
    step = parseInt(getStyle(elem, attr)) < target ? step : -step;
    clearInterval(elem.out);
    elem.out = setInterval(function () {
        
        var n = parseInt(getStyle(elem, attr)) + step;
        if ((n <= target && step) < 0||(n >= target && step > 0)) {
            n = target;
            clearInterval(elem.out);
        }
        elem.style.left = n + "px";

    }, 30);
}
``