javascript - 当已经选择了数组中的 DOM 元素时,如何防止 javascript 函数运行?

标签 javascript html arrays dom

我有一个脚本,它根据当前选择的数组中的哪个气泡为我提供动态 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/

相关文章:

javascript - 如何将空数组放入模板字符串

c# - 遍历数组并找到部分字符串

Python,识别循环中的文件给出错误: setting an array element with a squence

javascript - 嵌套 ES6 类?

javascript - 如何使用 jquery validate 用最少的一个输入进行验证?

javascript - 无法使用服务 AngularJS - 'Cannot read property ' prototype' of undefined'

javascript - 当 Angular 没有返回数据时隐藏和显示元素

javascript - 在JQuery Timer中添加时间按钮

javascript - 是否可以在 HTML 中的 'onclick' 上运行 .exe 或 .bat 文件

java - 仅显示数组中大于 45 的数字(我是一个完全的初学者)