js触发transition过渡动画

当元素本身为display:none时,若此时想通过js先将其变为display:block并且随后再触发其他想要的transition过渡效果,需要在js改变其为display:block后用setTimeout延迟10ms左右的时间再去设置其他过渡动画,否则过渡动画不会触发。另外,如果样式写在HTML代码中,用js设置className是没有动画效果的。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <style type="text/css">
        #ondiv{
            background: #000;
            width: 200px;
            height: 50px;
        }
        .test{
            display: none;
            background: red;
            width: 100px;
            height: 100px;
           
        }
        .box1{
            background: red;
            width: 200px;
            height: 200px;
            transition: all 1s;
            -moz-transition: all 1s;
            -webkit-transition: all 1s;
            -o-transition:all 1s;
        }
       .test-hover{
           display: block;
           ;
        }
    </style>
    <body>
        <div id="ondiv">JS transition</div><p></p>
        <div id="div" class="test"></div>
        <script type="text/javascript">
            //onmouseover
            document.getElementById("ondiv").onclick=function(){
                document.getElementById("div").className = 'test-hover test';
                setTimeout(function(){document.getElementById("div").className = 'box1'},10)
                //document.getElementById("div").style.width="200px"
                //document.getElementById("div").style.height="200px"
            }
            document.getElementById("ondiv").onmouseleave=function(){
                document.getElementById("div").className = 'test';
                //document.getElementById("div").style.width="200px"
                //document.getElementById("div").style.height="200px"
            }
        </script>
    </body>
</html>

效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值