简体   繁体   English

如何在JavaScript中添加暂停?

[英]How do I add a pause in JavaScript?

I have a div like this: 我有这样的股利:

<div style="width: 0%;"></div>

How can I change the css of width to 100% (and wait until it reaches 100%) before changing more elements? 如何在更改更多元素之前将width的css更改为100% (并等待其达到100%)?

For example: 例如:

$('div').css('width', '100%', function() {
    $('div').css('color', 'red');
});

Obviously this doesn't work, but how can I make it work? 显然这是行不通的,但是我如何使它行得通呢?

You can just use a timer to wait before processing some more code: 您可以只使用计时器来等待,然后再处理更多代码:

$('div').css('width', '100%');
setTimeout(function(){
    $('div').css('color','red');
}, 2000);

JSFiddle JSFiddle

Use jQuery animate() 使用jQuery animate()

$("div").animate({
    width:"100%" 
  }, 2000, function() {
    //On Animation complete
    $('div').css('color', 'red');
  });

Fiddle 小提琴

You can do it a number of ways. 您可以通过多种方式进行操作。 One way is to use CSS transitions: 一种方法是使用CSS过渡:

.yourDiv {
    width: 0%;
    -webkit-transition: width;
    -webkit-transition-duration: 3s;
    background: yellow;
}

.yourDiv.wide {
    width: 100%;
}

Then, to animate, apply the class via jQuery: 然后,要制作动画,请通过jQuery应用该类:

$('.yourDiv').addClass('wide')

To do something after it's done animating, use the webkitTransitionEnd event: 要在完成动画处理后执行一些操作,请使用webkitTransitionEnd事件:

$('.yourDiv')
    .addClass('wide')
    .one('webkitTransitionEnd', function(){
        $('this').css('background','red')
    })

If you wan to wait for a period of time after the animation finished before triggering your next style change, wrap it in a setTimeout: 如果要在动画结束后等待一段时间才能触发下一个样式更改,请将其包装在setTimeout中:

var $yourDiv = $('.yourDiv') var $ yourDiv = $('。yourDiv')

$yourDiv
    .addClass('wide')
    .one('webkitTransitionEnd', function(){
            setTimeout(function(){
                $yourDiv.css('background','red')
            },2000)
    })

fiddle: http://jsfiddle.net/22fPQ/1/ 小提琴: http//jsfiddle.net/22fPQ/1/

(note the above is webkit-centric. Use other browser CSS prefixes as needed to support) (请注意,以上内容是以webkit为中心的。请根据需要使用其他浏览器CSS前缀以进行支持)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM