0

我在我的网站上设置了 3 个 div,目前我正在使用 CSS3 通过更改背景颜色来突出显示每个 div 5 秒。所以第一个 div 突出显示 5 秒,然后是第 2 个,然后是第 3 个。我可以用 Javascript 实现同样的目标吗?

我的html是

<a href=""><div class="highlight" id="caption2">
Text1
</div></a>
<a href=""><div class="highlight" id="caption3">
Text2</div></a>
<a href="">
<div class="highlight" id="caption4">
Text3</div></a>

JS

      $("div.highlight").each(function (i) {
    var $self = $(this);
    setTimeout(function () {
        $self.removeClass("highlight")
        $self.addClass("caption");
        setTimeout(function () {
         $self.addClass("highlight");
            $self.removeClass("caption");
        }, 1000);
    }, i * 1000);
});

CSS

#caption2 {
    position:absolute;
    top:10px;
    left:-20px;
    z-index:50;
    padding-left:10px;
    padding-right:20px;
    padding-top:15px;
    padding-bottom:15px;
    color:#fff;
    font-family: 'Droid Sans', sans-serif;
    overflow:hidden;

}
#caption3 {
    position:absolute;
    top:70px;
    left:-20px;
    z-index:70;
    padding-left:10px;
    padding-right:20px;
    padding-top:15px;
    padding-bottom:15px;
    color:#fff;
    font-family: 'Droid Sans', sans-serif;
        overflow:hidden;


}
#caption4 {
    position:absolute;
    top:130px;
    left:-20px;
    z-index:50;
    padding-left:10px;
    padding-right:20px;
    padding-top:15px;
    padding-bottom:15px;
    color:#fff;
    font-family: 'Droid Sans', sans-serif;
        overflow:hidden;


}

.highlight {
    background-color:#000;
}
.caption {
    background-color:#f1583c;   
    color:yellow;   
}
4

1 回答 1

0

Sure! Nothing simpler than this:

var divs = document.getElementsByTagName("div")

for(var i = 0; i < divs.length; i++) {
    setTimeout(function(n){
        divs[n].className = "highlight";
    }, i * 1000, i);
}

http://fiddle.jshell.net/e4Qv4/

Or if you want it more jQuery'ished, take something like this:

$("div").each(function(i){
    var self = this;
    setTimeout(function(){
        self.className = "highlight";
    }, i * 1000);
});

http://fiddle.jshell.net/e4Qv4/1/

Update

Your main problem is the css-selector specificity... An ID gets an higher rate then a class. The other thing is, that you've misunderstood my solution. Read a bit about the Sizzle-Selector engine, which is built in jQuery, that should help you.

于 2013-06-10T17:07:01.120 回答