练习9_三道杠.html 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. div{
  9. width: 200px;
  10. height: 50px;
  11. background-color: red;
  12. margin:20px 0;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <div class="box"></div>
  18. <div class="box"></div>
  19. <div class="box"></div>
  20. <script>
  21. var aBox = document.getElementsByClassName("box");
  22. // this只能指向调用自己的对象
  23. // 方法二通过函数去分配工作
  24. // 循环给每一条杠绑定事件
  25. for(var i=0;i<aBox.length;i++){
  26. // 绑定鼠标移入事件
  27. aBox[i].onmouseenter = function(){
  28. // 调用控制元素变长的方法
  29. addWidth(this);
  30. }
  31. // 绑定鼠标移出事件
  32. aBox[i].onmouseleave = function(){
  33. // 调用控制元素变短的方法
  34. reduceWidth(this);
  35. }
  36. }
  37. // 定义控制元素变短的方法
  38. function reduceWidth(obj){
  39. //第一步 清除控制元素变长的定时器
  40. clearInterval(obj.timer1);
  41. // 给当前对象绑定一个timer2 用来装载变短的定时器
  42. obj.timer2 = setInterval(function(){
  43. if(obj.offsetWidth <= 200){
  44. clearInterval(obj.timer2);
  45. }
  46. obj.style.width = obj.offsetWidth - 10 + "px";
  47. },16);
  48. }
  49. // 定义控制元素变长的方法
  50. function addWidth(obj){
  51. // 第一步 清除控制元素变短的定时器
  52. clearInterval(obj.timer2);
  53. // 给当前对象绑定一个timer1 用来装载变长的定时器
  54. obj.timer1 = setInterval(function(){
  55. if(obj.offsetWidth >= 600){
  56. clearInterval(obj.timer1);
  57. }else{
  58. obj.style.width = obj.offsetWidth + 10 + "px";
  59. }
  60. },16);
  61. }
  62. // 方法一 所有的工作都由事件自己去处理
  63. // // 为三条杠循环绑定事件
  64. // for(var i=0;i<aBox.length;i++){
  65. // // 给每一条杠加上一个timer1用来装载变长的定时器
  66. // aBox[i].timer1 = null;
  67. // // 绑定鼠标移入事件
  68. // aBox[i].onmouseenter = function(){
  69. // clearInterval(this.timer2);
  70. // // 定义局部变量that 代替this 那么函数内再有函数就可以使用this了
  71. // var that = this;
  72. // // 控制三条杠的宽度增加
  73. // this.timer1 = window.setInterval(function(){
  74. // if(that.offsetWidth >= 600){
  75. // clearInterval(that.timer1);
  76. // }else{
  77. // that.style.width = that.offsetWidth + 10 + "px";
  78. // }
  79. // },16);
  80. // }
  81. // // 给每一条杠加上一个timer2 用来装载变短的定时器
  82. // aBox[i].timer2 = null;
  83. // // 绑定鼠标移出事件
  84. // aBox[i].onmouseleave = function(){
  85. // clearInterval(this.timer1);
  86. // var that = this;
  87. // this.timer2 = setInterval(function(){
  88. // if(that.offsetWidth <= 200){
  89. // clearInterval(that.timer2);
  90. // }else{
  91. // that.style.width = that.offsetWidth - 10 + "px";
  92. // }
  93. // },16);
  94. // }
  95. // }
  96. </script>
  97. </body>
  98. </html>