javascript - 纯JS实现JQUERY里animate效果(效果实现整理后)

查看:184
本文介绍了javascript - 纯JS实现JQUERY里animate效果(效果实现整理后)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

如题,自己试着用纯JS写了下面代码,实现鼠标一上去DIV宽和高的值增大的动画效果。但是一直报错,特意来向各位大神请教,和希望给点思路,如何才能更好的实现。。。。。(现在效果实现了,但是还是有些问题,就是不能随意的移开鼠标开始缩回,鼠标放回开始放大,求大神,给个思路和建议,还有就是感觉我这样写特别笨,有没更简洁的方式。。。。。)


<!DOCTYPE html>
<html>
<head>
    <title>纯JS实现animate</title>
    <meta charset = "utf-8">
    <style>
        #change {width:100px;height:100px;background-color: red;margin:100px auto;}
    </style>
</head>
<body>
   <div id = "change"></div>
</style>
<script type="text/javascript">
    function animateself (int){

        var div = document.getElementById("change");
        div.addEventListener("mouseover",function(){
            
            var timer = setInterval(function(){
                
           var wid = window.getComputedStyle(div,null).getPropertyValue("width");
           var heig = window.getComputedStyle(div,null).getPropertyValue("height");
              //alert(wid);
              heig = heig.replace("px","");
              heig = parseInt(heig);
              wid = wid.replace("px","");
              wid = parseInt(wid);
           div.style.width = (wid+1)+"px";
           div.style.height = (heig+1)+"px";
           //div.style.width = "200px"

           //alert(wid);
           if(wid>=int&&heig>=int){
               clearInterval(timer);
           }
        },1)  
     })

        div.addEventListener("mouseout",function(){
            var timer = setInterval(function(){
                
           var wid = window.getComputedStyle(div,null).getPropertyValue("width");
           var heig = window.getComputedStyle(div,null).getPropertyValue("height");
              //alert(wid);
              heig = heig.replace("px","");
              heig = parseInt(heig);
              wid = wid.replace("px","");
              wid = parseInt(wid);
           div.style.width = (wid-1)+"px";
           div.style.height = (heig-1)+"px";
           //div.style.width = "200px"

           //alert(wid);
           if(wid<=100&&heig<=100){
               clearInterval(timer);
           }
        },1)  
    })
       
    }   
     
    animateself(500);
    
</script>
</body>
</html>

解决方案

setInterval 是一个 timer,不停止会一直跑下去,至少在动画完成之后应该 clearInterval 吧

这篇关于javascript - 纯JS实现JQUERY里animate效果(效果实现整理后)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆