页面轮播

页面轮播(似java的线程)

<style>
        *{
            padding:0;
            margin:0;
        }
        #player{
            position:relative;
            margin:100px auto 0;
            width:800px;
            height: 350px;
            display: flex;
            justify-content: center;
        }
        #pa{
            flex-grow:1;
            background:transparent center no-repeat;
            transition:all 1s ease;
        }
        #control{
            position: absolute;
            bottom: 0;
            list-style: none;
            width: 106px;
            height: 24px;
            display: flex;
            justify-content: space-around;
            align-items: center;
        }
        #control>li{
            width:14px;
            height:14px;
            border-radius:7px;
            background-color:#AAA;
        }
style>

body里

<body>
    <div id="player">
        <a id="pa" href="">a>
        <ul id="control">
            <li>li>
            <li>li>
            <li>li>
            <li>li>
        ul>
    div>
    <script>
        //数据初始化
        var srcs=[
            {
                imgUrl:"imgs/beautify.png",
                url:"http//www.sina.com.cn"
            },{
                imgUrl:"imgs/heart.jpg",
                url:"http//www.sina.com.cn"
            },{
                imgUrl:"imgs/hospital.jpg",
                url:"http//www.sina.com.cn"
            },{
                imgUrl:"imgs/nurse.jpg",
                url:"http//www.sina.com.cn"
            },
        ];
        //声明
        var i = 0,t;    //var i = 0;var i = t;
        var clock;
        //获取元素对象
        var pa = document.getElementById("pa");
        var pi = document.getElementById("pi");
        var control = document.getElementById("control");
        var cs = control.children;
        //封装:数据切换(根据下标)
        function change(i){
            cs[i].style.backgroundColor = "#F40";
            cs[(i==0?3:i-1)].style.backgroundColor="#AAA";
            var s = srcs[i];
            pa.href = s.url;
            pa.style.backgroundImage = `url(${s.imgUrl})`;
        }
        //封装:启动时钟函数
        function start(){
            clock = setInterval(function(){
                if(++i>=srcs.length){
                    i = 0;
                }
                change(i);
            },3000);
        }
        //关闭时钟函数
        function stop(){
            t = i;
            clearInterval(clock);
        }
        //页面初始化:切换至下标0
        change(i);
        //调用启动时钟函数启动时钟
        start();
        //启动手动轮播,关闭自动轮播(回调)
        control.onmouseenter = stop;
        control.onmouseleave = start;
        //手动轮播
        for(const j in cs){
            cs[j].onmouseenter = function(){
                cs[i].style.backgroundColor = "#AAA";
                i = j;
                change(j);
            }
        }
    script>
body>

你可能感兴趣的:(前端,js,页面轮播,定时器)