這個問題在這里已經有了答案: 如何在下一個開始之前等待一個 jquery 影片完成? (6 個回答) 2 小時前關閉。
這是代碼
https://jsfiddle.net/zdu1efrj/
$(document).ready( function() {
// start box animation code
let animatedBox = $('.box');
animatedBox.css('backgound', 'red');
animatedBox.animate(
{
left: '500px',
height: '250px',
width: '250px'
}, 1000);
animatedBox.css('background', 'blue');
animatedBox.animate(
{
top: '500px',
height: '100px',
width: '100px'
}, 1000);
// end box animation code
});
我希望影片中的框是紅色的,只要它垂直移動然后將其顏色更改為藍色并向下移動。
為什么代碼沒有按順序執行?
為什么animatedBox.css('background', 'blue'); 好像是在完成之前執行
animatedBox.animate(
{
left: '500px',
height: '250px',
width: '250px'
}, 1000);```
?
uj5u.com熱心網友回復:
這里的問題是因為animate()呼叫實際上是異步的,因為操作被放置在佇列中并在以后運行。然而,css()呼叫沒有排隊/異步,因此立即執行。
要解決此問題,請使用該animate()方法的回呼引數,以便在第一個影片序列完成后更改元素的顏色:
animatedBox.animate({
left: '500px',
height: '250px',
width: '250px'
}, 1000, function() {
animatedBox.css('background', 'blue');
});
然而,這一切都可以通過單獨使用 CSS 來更有效、更高效地實作:
body { position: relative; }
.box {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
position: absolute;
background-color: red;
animation: box-movement 2s forwards;
}
@keyframes box-movement {
50% {
left: 500px;
top: 0;
height: 250px;
width: 250px;
background-color: red;
}
100% {
left: 500px;
top: 500px;
height: 100px;
width: 100px;
background-color: blue;
}
}
<div class="box"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/373257.html
標籤:javascript html 查询 css
