CSS/HTML/JS實現圖片輪播

來源:互聯網
上載者:User

標籤:css   href   title   設定   pretty   預設   lis   otto   ram   

實現原理將點擊的a標籤的href屬性值賦給img標籤的src屬性,這樣有個好處,就是如果瀏覽器不支援js的話,點擊a標籤也可跳轉到圖片地址看到圖片,不會影響內容的呈現

註:需要匯入jquery庫

html代碼

<div class="banner"> <img src="1.png"> <ul> <li><a href="1.png">1</a></li> <li><a href="2.png">2</a></li> <li><a href="3.png">3</a></li> <li><a href="4.png">4</a></li> </ul></div>
css代碼
/* 先取消預設樣式 */a { text-decoration: none; }ul { list-style-type: none; }ul, li { padding: 0; margin: 0;}.banner li { float: left;}.banner img { width: 600px; height: 400px;}/* relative和absolute用於控制切換按鈕位置 */.banner { position: relative; width: 600px; height: 400px; margin: auto;}.banner ul { position: absolute; right: 10px; bottom: 10px;}.banner ul li {margin-left: 5px;}.banner ul li a { display: inline-block; width: 20px; height: 20px; background-color: #8c8c8c; text-align: center; border-radius: 50%; /* 讓按鈕變圓形 */ color: #FFF}
js代碼

匯入jquery庫

<script src="jquery.js"></script>
$(document).ready(function(){  // 在一開始綁定a的點擊切換輪播圖事件 $(".banner>ul>li>a").click(function(){ banner(this); return false; }); bannerRoll();});// 用a標籤按鈕切換輪播圖function banner(obj) { // obj 當前標籤 var img = $(obj).parent().parent().prev(); $(img).attr("src", $(obj).attr("href"));}var t; // 用於標識定時器function bannerRoll() { t = setInterval(showPic, 3000); // 設定每三秒調用換圖函數換張圖}var x = 0; // 全域變數,記錄當前第幾張輪播圖function showPic() { // 擷取a父標籤li的個數,輪流播放 var arr_uls = $(".banner>ul"); arr_uls.each(function() { // 遍曆ul標籤,給它的img換張圖 if (x >= $(this).children().length) x = 0; $(this).prev("img").attr("src", arr_uls.children("li").eq(x).children("a").attr("href")); }); x++;}//滑鼠經過盒子時,清除定時$(".banner").mouseenter( function(){ clearInterval(t);}).mouseleave( function(){ //滑鼠離開盒子時,再次定時 bannerRoll();});

CSS/HTML/JS實現圖片輪播

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.