[英]In jQuery, how to use multiple delay() methods with css()?
我怎樣才能實現以下功能,如果只有一個延遲我可以使用setTimeout:
$(this).css().delay().css().delay().css();
jQuery“.delay()”API都是關於“效果隊列”的。 它實際上立即返回。
如果您沒有動畫CSS更改,唯一的方法是使用“setTimeout()”。
可能會讓事情更愉快的一件事是將CSS更改構建到數組中:
var cssChanges = [
{ delay: 500, css: { backgroundColor: "green", fontSize: "32px" }},
{ delay: 1000, css: { backgroundColor: "blue", textDecoration: "underline" }},
{ delay: 750, css: { position: "relative", marginLeft: "5px" }}
];
然后,您可以使用單個例程遍歷具有所需延遲的列表:
function doChanges(cssChanges) {
var index = 0;
function effectChanges() {
$('whatever').css(cssChanges[index].css);
if (++index < cssChanges.length) {
setTimeout(doChanges, cssChanges[index].delay);
}
}
setTimeout(effectChanges, cssChanges[0].delay);
}
你可以把它變成一個插件,但如果你打算這樣做,最好弄清楚如何使你的插件與jQuery中現有的動畫隊列設施一起玩。
這對你有用:)
// Delay to CSS Properties
var cssChanges = [
{
delay: 500,
css: {
color: 'red'
}},
{
delay: 1500,
css: {
color: 'blue'
}},
{
delay: 500,
css: {
color: 'yellow'
}}
];
var element = $('div'),
lastDelay = 0;
$.each(cssChanges, function(i, options) {
lastDelay += parseInt(options.delay);
setTimeout(function() {
element.css(options.css);
}, lastDelay);
});
jsFiddle 。
你也可以把它變成一個jQuery插件。
$.fn.delayCss = function(cssChanges) {
$(this).each(function() {
var element = $(this),
lastDelay = 0;
$.each(cssChanges, function(i, options) {
lastDelay += parseInt(options.delay);
setTimeout(function() {
element.css(options.css);
}, lastDelay);
});
});
}
jsFiddle 。
css
不是效果,它立即發生。 如果你想在交錯的時間進行多次css
更改, setTimeout
正是你想要的:
var $target = $("#target");
$target.css("color", "blue");
setTimeout(function() {
$target.css("color", "red");
setTimeout(function() {
$target.css("color", "green");
}, 500);
}, 500);
如果您正在嘗試使用css
,那么您可以使用animate
代替(例如,數字屬性而不是上面的顏色),那么如果您使用animate
代替css
,那么您的代碼將會起作用。
$("#target")
.animate({paddingLeft: "50px"})
.delay(500)
.animate({paddingLeft: "25px"})
.delay(500)
.animate({paddingLeft: "0px"});
您仍然可以使用setTimeout。 你只需要其中幾個。
或者你可以使用持續時間為0
而不是.css()
.animate()
.css()
:
示例: http : //jsfiddle.net/6sewU/
$(this).animate({prop:'value'},0).delay(1000)
.animate({prop:'value'},0).delay(1000)
.animate({prop:'value'},0);
請注意,如果使用.animate()
設置顏色,則需要安裝.animate()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.