123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- <!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{
- height: 50px;
- width: 200px;
- background-color: red;
- }
- </style>
- </head>
- <body>
- <div class="box"></div>
- <script>
- var oBox = document.getElementsByClassName("box")[0];
- var timer1 = null;
- var timer2 = null;
-
- // 鼠标移入,宽度增加
- oBox.onmouseenter = function(){
- // 清除另一个变短的定时器
- clearInterval(timer2)
- // 设定定时函数不断增加元素宽度
- timer1 = setInterval(function(){
- // 判断宽度是否大于600px 如果大于600px 清除定时器
- if(oBox.offsetWidth >= 600){
- clearInterval(timer1);
- }else{
- // 每执行一次增加10px
- oBox.style.width = oBox.offsetWidth + 10 + "px";
- }
- },16);
- }
- // 鼠标移出,宽度减少
- oBox.onmouseleave = function(){
- // 清除另一个变长的定时器
- clearInterval(timer1);
- // 设定定时函数不断减少元素宽度
- timer2 = setInterval(function(){
- // 判断宽度是否小于200px 如果小于200px 清除定时器
- if(oBox.offsetWidth <= 200){
- clearInterval(timer2);
- }else{
- // 每执行一次减少10px
- oBox.style.width = oBox.offsetWidth - 10 + "px";
- }
- },16);
- }
- </script>
- </body>
- </html>
|