[英]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.