1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> * { margin: 0; padding: 0; } #container { margin: 10px 20px; } #container li { float: left; list-style: none; width: 60px; height: 60px; } </style> </head> <body> <div id="container"> <img src="img/picture-1.jpg" alt="狗屎"> <ul id="items"> <li><img src="img/thumb-1.jpg" alt=""></li> <li><img src="img/thumb-2.jpg" alt=""></li> <li><img src="img/thumb-3.jpg" alt=""></li> </ul> </div> <script> var img = document.querySelector('#container>img'); var images = document.querySelectorAll('#items img'); for (var i = 0; i < images.length; i += 1) { // 事件回调函数在for循环的时候并没有执行所以也取不到循环变量i当前的值 // JavaScript是动态弱类型语言可以在运行时动态的添加(或删除)对象的属性 images[i].picture = 'img/picture-' + (i + 1) + '.jpg'; images[i].addEventListener('mouseover', function(evt) { img.src = evt.target.picture; }); } </script> </body> </html>
|