javascript 如何使网页中的图标闪烁/闪烁
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16291863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make an icon flash/blink, which is present in a web page
提问by Anuj Balan
I started working on advanced java few days before(too late to start on that, I know). I am stuck with a specific task of making an icon (which is present on the task bar) blink. This blinking should happen based on a specific condition, which means that it can be achieved using javascript
.
几天前我开始研究高级 Java(我知道为时已晚)。我被困在使图标(出现在任务栏上)闪烁的特定任务。这种闪烁应该基于特定条件发生,这意味着可以使用javascript
.
I have been searching for a while now but is there a way to make an icon appear and disappear every 1 second or so to bring in the blinking effect ?
我已经搜索了一段时间,但是有没有办法让图标每 1 秒左右出现和消失一次以引入闪烁效果?
回答by Ryan
HTML
HTML
<img src='image/source' alt='blinking!' id='blinking_image' />
Javascript
Javascript
var img = document.getElementById('blinking_image');
var interval = window.setInterval(function(){
if(img.style.visibility == 'hidden'){
img.style.visibility = 'visible';
}else{
img.style.visibility = 'hidden';
}
}, 1000); //the 1000 here is milliseconds and determines how often the interval should be run.
This creates an anonymous function inside the setInterval
that runs every 1 second (1sec == 1000milisec). To see more about setInterval checkout the mdn here on it.
这会setInterval
在每 1 秒(1sec == 1000milisec)运行一次的内部创建一个匿名函数。要查看有关 setInterval 的更多信息,请查看此处的 mdn。
Each time it runs it checks to see if the img
is hidden
or visible
if it's hidden then it shows it if it's visible then it hides it. It does this by checking the style.visiblity
property. Which you can learn more about here on the mdn.
每次运行时,它都会检查是否img
存在hidden
或visible
是否隐藏,如果可见则显示它,然后将其隐藏。它通过检查style.visiblity
属性来做到这一点。您可以在 mdn 上了解更多信息。
回答by Eyal Benishti
Small fix
小修复
instead
反而
if(img.display == 'hidden')
use
利用
if(img.style.visibility == 'hidden')
回答by stu
You might find opacity works better because the image is still there, which means it is still clickable if necessary. Also you can add a clear interval to stop the flashing.
您可能会发现不透明度效果更好,因为图像仍然存在,这意味着如果需要,它仍然可以点击。您也可以添加一个清除间隔来停止闪烁。
var mycounter = 0
interval = window.setInterval(function () {
if (img.style.opacity == '0.1') {
img.style.opacity = '1';
mycounter = mycounter + 1
if (mycounter == 7) {
clearInterval(interval);
}
} else {
img.style.opacity = '0.1';
}
}, 500); //the 1000 here is milliseconds and determines how often the interval