循环遍历元素并添加/删除类

问题描述 投票:1回答:2

我想遍历每个h1 > a元素,添加,然后在一定的延迟后删除一个类,但它不起作用。

我究竟做错了什么?

$("h1 a").each(function() {
  $(this).addClass('glow').delay(2000).removeClass('glow');
});
a {
  color: #000;
  text-decoration: none;
  text-shadow: -1px 0px 1px rgba(150, 150, 150, 1);
}

h1 {
  text-align: center;
}

.glow {
  animation: glow .8s infinite alternate;
}

@keyframes glow {
  to {
    text-shadow: 0 0 6px #aaa;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>
  <a href="#">wellcome</a>,&nbsp;
  <a href="#">bonjoure</a>,&nbsp;
  <a href="#">bienvenido</a>,&nbsp;
  <a href="#">benvenuto</a>,<br/>
  <a href="#">добро пожаловать</a>,<br/>
  <a href="#">willkommen</a>
</h1>
jquery element each
2个回答
3
投票

好吧,忘了我说的话。这可以 - 但不是css动画,你自己。

var a = [];
$("h1 a").each(function(index) {
  a[index] = $(this);
  setTimeout(function() {
    a[index].addClass('glow').delay(500).queue(function(next) {
      a[index].removeClass('glow');
      next();
    });
  }, index * 500);
});
a {
  color: #000;
  text-decoration: none;
  text-shadow: -1px 0px 1px rgba(150, 150, 150, 1);
}

h1 {
  text-align: center;
}

.glow {
  background-color: yellow;
}

@keyframes glow {
  to {
    text-shadow: 0 0 6px #aaa;
  }
}
<h1>
  <a href="#">wellcome</a>,&nbsp;
  <a href="#">bonjoure</a>,&nbsp;
  <a href="#">bienvenido</a>,&nbsp;
  <a href="#">benvenuto</a>,<br/>
  <a href="#">добро пожаловать</a>,<br/>
  <a href="#">willkommen</a>
</h1>

用这些作为参考:

How to make delay between each loops of jQuery.each function? Callback to .delay()


1
投票

如果你想要发光效果并且应该在一段时间之后添加和删除类来生效,你可以像这样使用setInterval()

$("h1").each(function(i, item) {
  setInterval(function() {
    $(item).addClass('glow');

  }, 2000 + i)
  setInterval(function() {
    $(item).removeClass('glow');

  }, 2000 + i)

});
a {
  color: #000;
  text-decoration: none;
  text-shadow: -1px 0px 1px rgba(150, 150, 150, 1);
}

h1 {
  text-align: center;
}

.glow {
  animation: glow .8s infinite alternate;
}

@keyframes glow {
  to {
    text-shadow: 0 0 6px #aaa;
  }
}
<h1>
  <a href="#">wellcome</a>,&nbsp;
  <a href="#">bonjoure</a>,&nbsp;
  <a href="#">bienvenido</a>,&nbsp;
  <a href="#">benvenuto</a>,<br/>
  <a href="#">добро пожаловать</a>,<br/>
  <a href="#">willkommen</a>
</h1>
© www.soinside.com 2019 - 2024. All rights reserved.