我有一个脚本,它根据当前选择的数组中的哪个气泡为我提供动态 header 。但是,当已经选择了一个气泡并且用户单击同一个气泡时,我无法停止 js 函数的运行,并且它会暂时将标题的不透明度更改为 0。在这种情况下,我希望标题的不透明度保持为 1。这看起来相当简单,但我无法弄清楚。 The code on CodePen.
HTML:
<div id="bubbles">
<div onclick="bubbles(0); clearInterval(intrvl);" style="background:#da2225;"></div>
<div onclick="bubbles(1); clearInterval(intrvl);"></div>
<div onclick="bubbles(2); clearInterval(intrvl);"></div>
</div>
<div id="bubblecontent">
<h2>Header 1</h2>
</div>
Javascript:
function _(x){return document.getElementById(x);}
var ba, bi=0, intrvl;
var bca = [
'<h2>Header 1</h2>',
'<h2>Header 2</h2>',
'<h2>Header 3</h2>',
];
function bubbles(bi){
_("bubblecontent").style.opacity = 0;
for(var i=0; i < ba.length; i++){
ba[i].style.background = "#ccc";
}
ba[bi].style.background = "#da2225";
setTimeout(function(){
_("bubblecontent").innerHTML = bca[bi];
_("bubblecontent").style.opacity = 1;
}, 300);
}
window.addEventListener("load", function(){
ba = _("bubbles").children;
});
最佳答案
在函数气泡中,如果 bi 与之前的相同,则添加条件:
var prev = -1;
function bubbles(bi){
if (bi != prev){
// put the rest of your bubbles(bi) code put here
}
prev = bi;
}
关于javascript - 当已经选择了数组中的 DOM 元素时,如何防止 javascript 函数运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39651599/