批改狀態(tài):未批改
老師批語(yǔ):
用jQurey改寫輪播圖:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>輪播圖</title> <style> .box { width:1920px; height: 500px; } .box ul { padding: 0; margin: 0; } /*將全部圖片樣式默認(rèn)不顯示*/ .box ul:first-of-type li { display: none; list-style: none; } .box ul:last-of-type { text-align: center; margin-top: -50px; } .box ul:last-of-type li { list-style: none; display: inline-block; width: 30px; height: 30px; line-height: 30px; background-color: black; color: white; border-radius: 50%; margin: 0 5px; } .box ul:last-of-type li:hover { cursor: pointer; background-color: white; color: black; } </style> </head> <body> <div class="box"> <!-- 輪播圖片--> <ul class="slider"> <!-- jQuery中的遍歷數(shù)組從0開始顯示,所以將圖片名字改成0,1, 2--> <li id="active" style="display: block"><img src="static/images/banner0.jpg" alt=""></li> <li><img src="static/images/banner1.jpg" alt=""></li> <li><img src="static/images/banner2.jpg" alt=""></li> </ul> <!-- 切換按鈕--> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> </div> <script src="static/js/jquery-3.4.1.js"></script> <script> //原生JavaScript代碼 // 獲取到所有按鈕 // var lis = document.querySelectorAll('.box ul:last-of-type li'); // // 獲取當(dāng)前正在顯示的圖片 // var currentImg = document.querySelector('#active img'); // // // 點(diǎn)擊后切換圖片 // for (var i = 0; i < lis.length; i++) { // // 自定義索引,獲取到當(dāng)前正在顯示的圖片索引 // lis[i].index = i; // // 給每一個(gè)按鈕添加點(diǎn)擊事件 // lis[i].onclick = function () { // currentImg.src = 'static/images/banner'+parseInt(this.index+1) + '.jpg'; // }; // } // // // 用間歇式定時(shí)器, 每隔2秒隨機(jī)切換圖片 // setInterval(function () { // var n = Math.floor(Math.random()*3)+1; // currentImg.src = 'static/images/banner'+parseInt(n) + '.jpg'; // }, 2000); //jQuery改寫 var lis =$('.box ul:last-of-type li'); //獲取所有的按鈕 var currentImg = $('#active img')[0];//獲取焦點(diǎn)圖片 // //測(cè)試 console.log(lis); console.log(currentImg); //用$.each()遍歷數(shù)據(jù),直接在函數(shù)內(nèi)添加點(diǎn)擊函數(shù) $.each(lis,function (value,element) { $(element).on('click',function(){ console.log(value); currentImg.src='static/images/banner'+ value + '.jpg'; console.log(currentImg.text); $(element).css('background-color','#42426F');//選中顯示 //移除當(dāng)前顯示圖片函數(shù) remove(); }) }); //移出添加的圖片函數(shù) function remove(){ for(var i = 0; i<lis.length; i ++){ $(lis[i]).attr('style',''); } } setInterval(function () { //添加一個(gè)1至3的隨機(jī)數(shù) var n = Math.floor(Math.random()*3); currentImg.src = 'static/images/banner'+ parseInt(n) + '.jpg'; //用parseInt獲取整數(shù)輸出 for(var i = 0; i<lis.length; i ++) { $(lis[i]).attr('style', ''); } $(lis[n]).css('background-color','#42426F'); // $(lis[n]).css('color','black'); }, 2000); </script> </body> </html>
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
因?yàn)楸闅v數(shù)組是從0開始,所以將原有圖片名字改成0,1,2,三張
實(shí)際顯示效果(截取了其中一張圖片顯示):
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)