练习8_一道杠.html 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <style>
  8. .box{
  9. height: 50px;
  10. width: 200px;
  11. background-color: red;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. <div class="box"></div>
  17. <script>
  18. var oBox = document.getElementsByClassName("box")[0];
  19. var timer1 = null;
  20. var timer2 = null;
  21. // 鼠标移入,宽度增加
  22. oBox.onmouseenter = function(){
  23. // 清除另一个变短的定时器
  24. clearInterval(timer2)
  25. // 设定定时函数不断增加元素宽度
  26. timer1 = setInterval(function(){
  27. // 判断宽度是否大于600px 如果大于600px 清除定时器
  28. if(oBox.offsetWidth >= 600){
  29. clearInterval(timer1);
  30. }else{
  31. // 每执行一次增加10px
  32. oBox.style.width = oBox.offsetWidth + 10 + "px";
  33. }
  34. },16);
  35. }
  36. // 鼠标移出,宽度减少
  37. oBox.onmouseleave = function(){
  38. // 清除另一个变长的定时器
  39. clearInterval(timer1);
  40. // 设定定时函数不断减少元素宽度
  41. timer2 = setInterval(function(){
  42. // 判断宽度是否小于200px 如果小于200px 清除定时器
  43. if(oBox.offsetWidth <= 200){
  44. clearInterval(timer2);
  45. }else{
  46. // 每执行一次减少10px
  47. oBox.style.width = oBox.offsetWidth - 10 + "px";
  48. }
  49. },16);
  50. }
  51. </script>
  52. </body>
  53. </html>