123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
- <!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>
- .box{
- width: 300px;
- height: 50px;
- background-color: red;
- margin-bottom: 20px;
- }
- </style>
- </head>
- <body>
- <div class="box"></div>
- <div class="box"></div>
- <div class="box"></div>
- <script>
-
- var oBox = document.getElementsByClassName("box");
- var timer1 = null;
- var timer2 = null;
-
- // 方法一
- for(var i=0;i<3;i++){
- oBox[i].onmouseenter = function(){
- addWidthFun(this);
- }
- oBox[i].onmouseleave = function(){
- reduceWidthFun(this);
- }
- }
-
- function addWidthFun(obj){
- clearInterval(obj.timer2)
- obj.timer1 = setInterval(function(){
- if(obj.offsetWidth > 500){
- clearInterval(obj.timer1);
- return false;
- }
- obj.style.width = (obj.offsetWidth + 5) + "px";
- },16)
- }
- function reduceWidthFun(obj){
- clearInterval(obj.timer1)
- obj.timer2 = setInterval(function(){
- if(obj.offsetWidth < 300){
- clearInterval(obj.timer2);
- return false;
- }
- obj.style.width = (obj.offsetWidth - 5) +"px";
- },16)
- }
-
-
-
-
-
-
-
-
- // 方法二
- // 对象的方法内this指向的是当前对象,但如果方法内嵌套了函数那么函数内的this指向的是window
- // 当出现函数嵌套的时候, 内部函数可以使用外部函数的变量
- // for(var i=0;i<3;i++){
- // // 创建一个新属性timer给到每一个横向,用作控制变长的setInterval
- // oBox[i].timer = null;
- // oBox[i].onmouseenter = function(){
- // var that = this;
- // clearInterval(that.timer2)
- // // console.log(this);
- // that.timer = setInterval(function(){
- // // console.log(that);
- // that.style.width = (that.offsetWidth +5) +"px";
- // if(that.offsetWidth > 500){
- // clearInterval(that.timer)
- // }
- // },16)
- // }
- // }
- // for(var j=0;j<3;j++){
- // // 创建新属性timer2给到每一个横向,用作控制变短的setInterval
- // oBox[j].timer2 = null;
- // oBox[j].onmouseleave = function(){
- // var that = this;
- // clearInterval(that.timer)
- // that.timer2 = setInterval(function(){
- // that.style.width = (that.offsetWidth - 5) + "px";
- // if(that.offsetWidth<300){
- // clearInterval(that.timer2)
- // }
- // },16)
- // }
- // }
- // var a = 0;
- // a = 1;
- // a = 2;
- // a = 3;
- // console.log(a);
-
- // 鼠标移入控制元素不断变长
- // oBox.onmouseenter = function(){
- // clearInterval(timer2);
- // timer1 = setInterval(function(){
- // oBox.style.width = (oBox.offsetWidth+5)+"px";
- // if(oBox.offsetWidth>500){
- // clearInterval(timer1);
- // }
- // },16)
- // }
- // // 鼠标移出后控制元素不断变短
- // oBox.onmouseleave = function(){
- // clearInterval(timer1);
- // timer2 = setInterval(function(){
- // oBox.style.width = (oBox.offsetWidth-5) + "px";
- // if(oBox.offsetWidth<300){
- // clearInterval(timer2)
- // }
- // },16)
- // }
-
- </script>
- </body>
- </html>
|