【JavaScript】用原生js来实现链式运动以及同时执行多种运动

链式运动框架

function getStyle(obj, name) {
	if (obj.currentStyle) {
		return obj.currentStyle[name]
	} else {
		return getComputedStyle(obj, false)[name]
	}
}

function startMove(obj, attr, iTarget, fnEnd) {
	clearInterval(obj.timer)
	obj.timer = setInterval(function () {
		var cur = 0
		if (attr == 'opacity') {
			cur = Math.round(parseFloat(getStyle(obj, attr)) * 100)
		} else {
			cur = parseInt(getStyle(obj, attr))
		}
		var speed = (iTarget - cur) / 3
		speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)
		if (cur == iTarget) {
			clearInterval(obj.timer)
			if(fnEnd)fnEnd() //如果有回调函数,执行
		} else {
			if (attr == 'opacity') {
				obj.style.opacity = (cur + speed) / 100
			} else {
				obj.style[attr] = cur + speed + 'px'
			}
		}
	}, 30)
}

实例:鼠标移入先变宽、变高、改变透明度,鼠标移出,改变透明度、变矮、变窄

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #div1 {
            width: 100px; height: 100px; background-color: #000; opacity: 0.3;}
    </style>
</head>

<body>
    <div id="div1"></div>
    <script src="move.js"></script>
    <script>
        window.onload = function () {
            var oDiv = document.getElementById('div1')
            oDiv.onmouseover = function () {
                startMove(oDiv, 'width', 300, function () {
                    startMove(oDiv, 'height', 300, function () {
                        startMove(oDiv, 'opacity', 100)
                    })
                })
            }
            oDiv.onmouseout = function(){
                startMove(oDiv, 'opacity', 30, function(){
                    startMove(oDiv, 'height', 200, function(){
                        startMove(oDiv, 'width', 200)
                    })
                })
            }

        }
    </script>
</body>

完美运动框架

function getStyle(obj, name) {
	if (obj.currentStyle) {
		return obj.currentStyle[name]
	} else {
		return getComputedStyle(obj, false)[name]
	}
}

function startMove(obj, json, fnEnd) {
	clearInterval(obj.timer)
	obj.timer = setInterval(function () {
		var bStop = true
		for (var attr in json) {
			var cur = 0
			if (attr == 'opacity') {
				cur = Math.round(parseFloat(getStyle(obj, attr)) * 100)
			} else {
				cur = parseInt(getStyle(obj, attr))
			}
			var speed = (json[attr] - cur) / 3
			speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)
			if (cur != json[attr]) //如果运动为执行完毕,将 bStop 设置为 false
			{
				bStop = false
			}
			if (attr == 'opacity') {
				obj.style.opacity = (cur + speed) / 100
			} else {
				obj.style[attr] = cur + speed + 'px'
			}
		}
		if (bStop) { //只有当所有运动执行完毕时,才会清除定时器
			clearInterval(obj.timer)
			if (fnEnd) fnEnd()
		}
	}, 30)
}

猜你喜欢

转载自blog.csdn.net/meichaoWen/article/details/112853957