![](/img/trans.png)
[英]How to delay jquery hide on mousedown until CSS animation completes?
[英]How to delay css animation in jQuery
如何在jQuery中延遲動畫? 我嘗試使用setTimeout,但無法正常工作。
$(document).ready(function(){
$('button').hover(function(){
window.setTimeout(function(){
$(this).css('transform', 'scale(1.3, 1.3)');
},500);
}, function(){
$(this).css('transform', 'none');
});
});
雖然提供了一個漂亮的CSS示例作為替代答案,但針對您的具體情況,我建議您不要這樣做。 原因是動畫(盡管已延遲)仍在懸停時進行了初始化,並且由於過渡涉及scale
,因此在延遲期間會使文本模糊。
關於Javascript解決方案,一旦進入setTimeout
,就失去了$(this)
的范圍。 我會在setTimeout
之前聲明它,然后使用該聲明而不是$(this)
,就像這樣...
$(document).ready(function(){
$('button').hover(function(){
var myButton = $(this);
window.setTimeout(function(){
myButton.css('transform', 'scale(1.3, 1.3)');
},500);
}, function(){
myButton.css('transform', 'none');
});
});
實現想要的最簡單方法是僅使用CSS,主要是transition
屬性。
5aledmaged在他的回答中已經證明了這一點
這是一個JS解決方案:
它不工作的原因是因為this
你傳遞到回調中setTimeout
是不一樣的this
傳遞到回調中.hover()
$('button').hover(function() {
var outer = this;
setTimeout(function(){
outer === this; // false
}, 500);
// ...
您可以做的是保存對外部this
的引用,並在內部回調中使用它:
var $this = $(this); // save the `this` you need
window.setTimeout(function() {
$this.css('transform', 'scale(1.3, 1.3)'); // and use it here
}, 500);
演示:
$('button').hover(function() { var $self = $(this); // save the `this` you need window.setTimeout(function() { $self.css('transform', 'scale(1.3, 1.3)'); // and use it here }, 500); }, function() { $(this).css('transform', 'none'); });
button { margin: 50px 0 0 200px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button> Check </button>
或使用箭頭函數保持其外部上下文:
window.setTimeout(() => {
$(this).css('transform', 'scale(1.3, 1.3)'); // `this` is the same as outer `this`
}, 500);
演示:
$('button').hover(function() { var $self = $(this); // save the `this` you need window.setTimeout(() => { $(this).css('transform', 'scale(1.3, 1.3)'); // `this` is the same as outer `this` }, 500); }, function() { $(this).css('transform', 'none'); });
button { margin: 50px 0 0 200px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button> Check </button>
您無需使用jQuery就可以實現整體效果。 只需使用CSS:
button {
margin: 50px 0 0 200px;
transition: transform 1s ease .5s; /* delay equals .5s */
}
button:hover {
transform: scale(1.3);
}
這是更新的JSFiddle 。
問題是值this
。 隨着setTimeout
的變化。 可以通過存儲獲得適當的對象this
在一個變量中,然后使用一個封閉件:
$(document).ready(function(){
$('button').hover(function(){
var trueThis = this; // <--
window.setTimeout(function(){
$(trueThis).css('transform', 'scale(1.3, 1.3)'); // <--
},500);
}, function(){
$(this).css('transform', 'none');
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.