123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- div{
- width: 200px;
- height: 50px;
- background-color: red;
- margin:20px 0;
- }
- </style>
- </head>
- <body>
- <div class="box"></div>
- <div class="box"></div>
- <div class="box"></div>
- <script>
- var aBox = document.getElementsByClassName("box");
- // this只能指向调用自己的对象
- // 方法二通过函数去分配工作
- // 循环给每一条杠绑定事件
- for(var i=0;i<aBox.length;i++){
- // 绑定鼠标移入事件
- aBox[i].onmouseenter = function(){
- // 调用控制元素变长的方法
- addWidth(this);
- }
- // 绑定鼠标移出事件
- aBox[i].onmouseleave = function(){
- // 调用控制元素变短的方法
- reduceWidth(this);
- }
- }
- // 定义控制元素变短的方法
- function reduceWidth(obj){
- //第一步 清除控制元素变长的定时器
- clearInterval(obj.timer1);
- // 给当前对象绑定一个timer2 用来装载变短的定时器
- obj.timer2 = setInterval(function(){
- if(obj.offsetWidth <= 200){
- clearInterval(obj.timer2);
- }
- obj.style.width = obj.offsetWidth - 10 + "px";
- },16);
- }
- // 定义控制元素变长的方法
- function addWidth(obj){
- // 第一步 清除控制元素变短的定时器
- clearInterval(obj.timer2);
- // 给当前对象绑定一个timer1 用来装载变长的定时器
- obj.timer1 = setInterval(function(){
- if(obj.offsetWidth >= 600){
- clearInterval(obj.timer1);
- }else{
- obj.style.width = obj.offsetWidth + 10 + "px";
- }
- },16);
- }
- // 方法一 所有的工作都由事件自己去处理
- // // 为三条杠循环绑定事件
- // for(var i=0;i<aBox.length;i++){
- // // 给每一条杠加上一个timer1用来装载变长的定时器
- // aBox[i].timer1 = null;
- // // 绑定鼠标移入事件
- // aBox[i].onmouseenter = function(){
- // clearInterval(this.timer2);
- // // 定义局部变量that 代替this 那么函数内再有函数就可以使用this了
- // var that = this;
- // // 控制三条杠的宽度增加
- // this.timer1 = window.setInterval(function(){
- // if(that.offsetWidth >= 600){
- // clearInterval(that.timer1);
- // }else{
- // that.style.width = that.offsetWidth + 10 + "px";
- // }
- // },16);
- // }
- // // 给每一条杠加上一个timer2 用来装载变短的定时器
- // aBox[i].timer2 = null;
- // // 绑定鼠标移出事件
- // aBox[i].onmouseleave = function(){
- // clearInterval(this.timer1);
- // var that = this;
- // this.timer2 = setInterval(function(){
- // if(that.offsetWidth <= 200){
- // clearInterval(that.timer2);
- // }else{
- // that.style.width = that.offsetWidth - 10 + "px";
- // }
- // },16);
- // }
- // }
- </script>
- </body>
- </html>
|