只进行一次div闪光

sah*_*ana 5 html javascript css

我想在特定的点击事件中使我的div闪光或突出显示一次.我尝试了以下代码

function blink() {
   var f = document.getElementById('divId');
   setInterval(function() {
      f.style.display = (f.style.display == 'none' ? '' : 'none');
   }, 500);
}
Run Code Online (Sandbox Code Playgroud)

但我一直在眨眼.我想只使用JavaScript.任何线索?

Pra*_*man 10

了解在JavaScript中使用两个计时器函数:

  • setTimeout - 在指定时间后做一次.
  • setInterval - 每指定时间无限次.

只需更换setTimeoutsetInterval:

function blink() {
   var f = document.getElementById('divId');
   setTimeout(function() {
      f.style.display = (f.style.display == 'none' ? '' : 'none');
   }, 500);
}
Run Code Online (Sandbox Code Playgroud)

或者,如果你想让它真的眨眼,那么就这样做,因为上面的只是翻转一次,你需要做两次:

function blink() {
   var f = document.getElementById('divId');
   setTimeout(function() {
      f.style.display = (f.style.display == 'none' ? '' : 'none');
   }, 500);
   setTimeout(function() {
      f.style.display = (f.style.display == 'none' ? '' : 'none');
   }, 1000);
}
Run Code Online (Sandbox Code Playgroud)

如果不是两次,请使用嵌套:

function blink() {
   var f = document.getElementById('divId');
   setTimeout(function() {
      f.style.display = (f.style.display == 'none' ? '' : 'none');
       setTimeout(function() {
          f.style.display = (f.style.display == 'none' ? '' : 'none');
       }, 500);
   }, 500);
}
Run Code Online (Sandbox Code Playgroud)

请参阅这两个功能的计时功能和秒数.


更新

一旦页面加载,看起来OP想要黄色淡化效果:

$(function () {
  $("#fade-it").delay(150).animate({
    "background-color": "#fc9"
  }, 350, function () {
    $("#fade-it").animate({
      "background-color": "#fff"
    }, 200);
  });
});
Run Code Online (Sandbox Code Playgroud)
* {font-family: 'Segoe UI', sans-serif; margin: 0; padding: 0; list-style: none;}
#fade-it {padding: 15px; text-align: center;}
Run Code Online (Sandbox Code Playgroud)
<script src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<div id="fade-it">
  Welcome!
</div>
Run Code Online (Sandbox Code Playgroud)

注意:我已经使用了jQuery和jQuery UI,我们也可以在纯CSS中执行.


更新:使用纯CSS动画.

* {
  font-family: 'Segoe UI', sans-serif;
  margin: 0;
  padding: 0;
  list-style: none;
}
#fade-it {
  padding: 15px;
  text-align: center;
}
@-webkit-keyframes yellow-fade {
  from {
    background: #f96;
  }
  to {
    background: #fff;
  }
}
@-moz-keyframes yellow-fade {
  from {
    background: #f96;
  }
  to {
    background: #fff;
  }
}
@keyframes yellow-fade {
  from {
    background: #f96;
  }
  to {
    background: #fff;
  }
}
#fade-it {
  -webkit-animation: yellow-fade 1s ease-in-out 0s;
  -moz-animation: yellow-fade 1s ease-in-out 0s;
  -o-animation: yellow-fade 1s ease-in-out 0s;
  animation: yellow-fade 1s ease-in-out 0s;
}
Run Code Online (Sandbox Code Playgroud)
<div id="fade-it">
  Welcome!
</div>
Run Code Online (Sandbox Code Playgroud)