基於jQuery實現水平輪播效果

效果圖

在這裏插入圖片描述

方法:使用動畫效果,讓第一幅圖的寬度逐漸變爲0px,然後將第一幅圖添加至父元素末尾

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>標題</title>
    <link rel="stylesheet" href="../css/reset.css">
    <script src="./jquery-3.4.1.min.js"></script>
    <style type="text/css">
        #box{
            width: 800px; height: 300px; 
            margin: 200px auto; 
            position: relative; 
            overflow: hidden;
        }
        #box ul{
            width: 3200px; height: 300px;
            position: absolute; top: 0px; left: -800px;
        }
        #box ul li{
            width: 800px; height: 300px; float: left;
        }
        #box ul li img{
            width: 800px; height: 300px;;
        }
    </style>
    <script>
        $(function(){
            // 滾動播放函數
            function gunDongBoFang(){      

                $("#box ul li:first").animate({width:"0px"}, 1000, function(){
                    $("#box ul").append($("#box ul li:first").width("800px"));
                });
            };

            // 定時器,每2秒執行一次
            var time = setInterval(gunDongBoFang, 2000);

            // 鼠標移入#box元素中,停止定時器
            $("#box").mouseenter(function(){
                clearInterval(time);
            });    

            // 鼠標移出#box元素後,開始定時器
            $("#box").mouseleave(function(){
                // setInterval(gunDongBoFang, 1000); 錯誤寫法,鼠標移入移出定時器會累加
                
                //鼠標移出時,開始定時器,並將定時器賦值給time變量,而當鼠標再次移入時,則剛好刪除上次的定時器,不會累加
                time = setInterval(gunDongBoFang, 2000);
            });    
        });
    </script>
</head>
<body>
    <div id="box">
        <ul>
            <li>
                <a href="#">
                    <img src="https://www.51zxw.net/NewAn/UploadFiles/20200609/202006090520504133.jpg">
                </a>
            </li>
            <li>
                <a href="#">
                    <img src="https://www.51zxw.net/NewAn/UploadFiles/20200608/202006080410588630.jpg">
                </a>
            </li>
            <li>
                <a href="#">
                    <img src="https://www.51zxw.net/NewAn/UploadFiles/20200608/202006080408097382.jpg">
                </a>
            </li>
            <li>
                <a href="#">
                    <img src="https://www.51zxw.net/NewAn/UploadFiles/20200624/202006240832286533.jpg">
                </a>
            </li>
        </ul>
    </div>
</body>
</html>

reset.css

*{margin: 0; padding: 0; box-sizing: border-box;}
body{font-size:16px; font-family:"微軟雅黑"; color: #333;}
b{font-weight: normal;}
i{font-style: normal;}
a, a:hover, a:active{text-decoration: none;  color: #333;}
input,textarea,select{outline: none;}
img{border: none; vertical-align: middle;}
li{list-style-type: none;}
.fl{float: left;}
.fr{float: right;}
.cl{clear: both;}
.clearfix::after{
    content: "";
    display: table;
    clear: both;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章