js_practice_4.html 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>轮播广告</title>
  6. <style>
  7. #adv {
  8. width: 600px;
  9. margin: 0 auto;
  10. }
  11. </style>
  12. </head>
  13. <body>
  14. <div id="adv">
  15. <img src="images/slide-1.jpg" width="600" alt="">
  16. </div id="adv">
  17. <script>
  18. // document.getElementById('标识') ---> HTMLElement [!]
  19. // document.getElementsByTagName('标签名') ---> NodeList
  20. // document.getElementsByClassName('类名') ---> NodeList
  21. // document.querySelector('样式表选择器') ---> HTMLElement [!]
  22. // document.querySelectorAll('样式表选择器') ---> NodeList [!]
  23. // firstChild / lastChild / children --- 获取子节点
  24. // parentNode --- 获取父节点
  25. // previousSibling / nextSibling --- 获取兄弟
  26. const img = document.querySelector('#adv>img')
  27. const imageNames = ['slide-1', 'slide-2', 'slide-3', 'slide-4']
  28. var imageIndex = 0
  29. function switchImage() {
  30. imageIndex += 1
  31. imageIndex %= imageNames.length
  32. img.src = 'images/' + imageNames[imageIndex] + '.jpg'
  33. }
  34. var timerId = setInterval(switchImage, 2000)
  35. img.addEventListener('mouseover', () => clearInterval(timerId))
  36. img.addEventListener('mouseout', () => {
  37. timerId = setInterval(switchImage, 2000)
  38. })
  39. </script>
  40. </body>
  41. </html>