一、实现目标:javascript控制多个div伸缩运动

二、效果图

三、代码

1.HTML代码


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</body>
</html>

2、CSS代码

<style>
        div {
            width: 100px;
            height: 100px;
            background: red;
            margin-bottom: 60px;
        }
 </style>
3.JavaScript代码

var timer = null;
        var oDivArray = document.getElementsByTagName('div');//类数组,获取所有div
        for (i = 0; i < oDivArray.length; i++) {
            oDivArray[i].onmouseenter = function () {
                startMove(this, 400);
            }
            oDivArray[i].onmouseleave = function () {
                startMove(this, 100);
            }

}

function getStyle(dom, attr) { if (window.getComputedStyle) { return window.getComputedStyle(dom, null)[attr];    //null为不获取伪类的样式 } else { window.currentStyle[attr] }

}

function startMove(dom, target) { clearInterval(dom.timer); var iSpeed = null, iCur = null;; dom.timer = setInterval(function () { iCur = parseInt(getStyle(dom, 'width')); iSpeed = (target - iCur) / 6; //不限于6,任何整数 iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed); if (iCur == target) { clearInterval(dom.timer); } else { dom.style.width = (iCur + iSpeed); } }, 30); }


您已经阅读00:00:00欢迎留言评论,喜欢的话就为作者点个赞或者赏颗糖吧! 分享