繁体   English   中英

更改按钮的背景颜色(开/关)

[英]Changing the background colour of a button (On/Off)

我已经查看了这个问题,但我没有使用 angular。

到目前为止,这是我的代码:

<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "#Bx")'>Bx</button>
<button id='By' type="button" onclick='toggleClickedBuz("Bx", "#Bx")'>By</button>
<button id='Bz' type="button" onclick='toggleClickedBuz("Bx", "#Bx")'>Bz</button>

像我这样的JS:

function toggleClickedBuz( bizStr , id ) {
    if(clickedBusinesses.includes(bizStr)){
       // removing duplicate element from that array, dependant on button pressed
       clickedBusinesses = clickedBusinesses.filter( cb => cb !== bizStr );
       document.getElementById( id ).style.backgroundColor='white';
    }else{
        // else push it to the array
       clickedBusinesses.push(bizStr)
       document.getElementById( id ).style.backgroundColor='red';
    }
    console.log(clickedBusinesses)
}

但我收到此错误:

未捕获的类型错误:无法读取 null 的属性“样式”

尽管在我的 CSS 中有这个:

.canvas .button-box button {
    border-radius: 2px;
    width: 10vw;
    margin-top: 0.5vh;
    background-color: whitesmoke;
}

有什么建议吗?

很简单,您不需要# in toggleClickedBuz("Bx", "#Bx") id不带# function getElementById()已经引用了 id。 所以你不需要指定使用#

你的 HTML 应该像

<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>Bx</button>
<button id='By' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>By</button>
<button id='Bz' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>Bz</button>

给出以下 HTML

<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "#Bx")'>Bx</button>

您将#Bx作为 id 参数传递给您的切换 function。 这导致 js 调用:

document.getElementById("#Bx");

但是getElementById function 不需要#前缀。 尝试将您的 HTML 更改为

<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>Bx</button>

修复您当前的问题

您的按钮中不需要# 这么多就够了:

<button id='Bx' type="button" onclick='toggleClickedBuz("Bx","Bx")'>Bx</button>
<button id='By' type="button" onclick='toggleClickedBuz("Bx","Bx")'>By</button>
<button id='Bz' type="button" onclick='toggleClickedBuz("Bx","Bx")'>Bz</button>

#是一个 CSS 选择器,用于选择您的 HTML id元素。 您可以通过以下方式在 CSS 中引用它们:

#Bx {
  color: #AAAAAA;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM