1、index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>同时运动</title>
</head>
<style>
*{margin: 0;padding: 0;}
.div{width: 200px;height: 100px;margin-bottom: 10px;background: pink;}
</style>
<body>
<div class="div" id="div"></div>
</body>
<script src="../js/myAnimal2.js"></script>
<script>
window.onload = () => {
const divElem = document.getElementById("div");
divElem.onmouseover = () => {
velocity(divElem,{"width":600,"height":200,"opacity":30});
}
divElem.onmouseout = () => {
velocity(divElem,{"width":200,"height":100,"opacity":100});
}
}
</script>
</html>
2、myAnimal.js
/**
* @param {*} elem 目标元素
* @param {*} json 动画变换属性及对应值
* @param {*} fn 动画完成后的回调函数
*/
function velocity(elem,json,fn){
elem.timer && clearInterval(elem.timer);
elem.timer = setInterval(() => {
let flag = true;
for (const attr in json) {
if (json.hasOwnProperty(attr)) {
let cur = parseInt(getStyle(elem,attr));
if(attr === "opacity"){
cur = Math.round(parseFloat(getStyle(elem,attr)) * 100);
}
if(json[attr] !== cur){
flag = false;
}
const speed = json[attr] > cur ? Math.ceil((json[attr] - cur) / 10) : Math.floor((json[attr] - cur) / 10);
if(attr === "opacity"){
elem.style[attr] = (cur + speed) / 100;
elem.style['filter'] = `alpha(opacity:${cur + speed})`;
}else{
elem.style[attr] = cur + speed + "px";
}
}
}
if(flag){
clearInterval(elem.timer);
if(fn && typeof fn === "function"){
fn();
}
return;
}
},30);
}
/**
* @param {*} elem 目标元素
* @param {*} attr 设置的属性
* @returns
*/
function getStyle(elem,attr){
if(elem.currentStyle){//IE下
return elem.currentStyle[attr];
}else{//主流下
return getComputedStyle(elem,null)[attr];
}
}