之前是用jquery的animate写动画,动画也比较好用,但是在涉及到动画完成之后的数据显示和变化(回调操作)时,效果就有点影响了。
$(".center-modal").animate({ width: "41.5rem" }, 500, "linear", ()=> {
// 执行传入的回调,做一些数据修改
callback();
console.log('测试文本')
})
原本是上面那样写,在我的电脑也没有问题,但是在其他好几位同事的电脑上,发现这个animate动画的回调执行了3次(打印了3次,debugger也确实卡了3次;但是在我电脑上就执行1次)验证了和浏览器无关,同样的浏览器,我和同事们的该动画回调执行次数不一样,无奈之下我只能寻找其他的写法来写动画。
最后参考了w3school的内容,具体链接:
https://www.w3school.com.cn/js/js_htmldom_animate.asp
最后上一下我改的代码,widthAdd 和 widthMinus 对应的就是 myMove函数
// 宽度变大的动画
widthAdd(targetWidth, callback = () => {}) {
let modal = this.$refs.centerModal;
// var elem = document.getElementById("animate");
let pos = 0;
let id = setInterval(frame, 5);
function frame() {
if (pos >= targetWidth) {
clearInterval(id);
// 这里可以在动画执行完毕之后进行一些回调操作
callback();
} else {
pos = pos + 0.5;
modal.style.width = pos + "rem";
}
}
},
// 宽度变小的动画
widthMinus(initWidth, callback = () => {}) {
let modal = this.$refs.centerModal;
// var elem = document.getElementById("animate");
let pos = initWidth;
let id = setInterval(frame, 5);
function frame() {
if (pos <= 0) {
clearInterval(id);
// 这里可以在动画执行完毕之后进行一些回调操作
callback();
} else {
pos = pos - 0.5;
modal.style.width = pos + "rem";
}
}
},
// 展示框关闭函数
closeModal() {
this.widthMinus(() => {
// 关闭之后重置一些数据
this.modalList = [];
this.btxxDetailsList = [];
this.modalListcon = false;
this.modalTitle = "详情信息";
this.firstOpen = true;
});
},
// 展示框打开函数, 入参的callback是为了更好的在openModal外部定义想要的回调操作
openModal(callback = () => {}) {
if (this.firstOpen) {
callback();
this.widthAdd();
this.firstOpen = false;
// $(".center-modal")
// .animate({ width: "41.5rem" }, 500)
// .promise()
// .done(() => {
// this.firstOpen = false;
// });
} else {
// 否则先关闭再打开
this.widthMinus(() => {
this.modalList = [];
this.btxxDetailsList = [];
this.modalListcon = false;
callback();
this.widthAdd();
this.firstOpen = false;
});
}
},