如何通过javascript动态更改按钮悬停颜色



我想更改所有按钮的悬停颜色以匹配我的网站主题。我有一个默认的颜色,但需要根据参考页面进行更改。我可以获得引用页面,但我不知道如何更改悬停样式。这就是我所拥有的:

var btn = {
hover: function (event) {
event.target.style.backgroundColor = "blue";
},
out: function (event) {
event.target.style.backgroundColor = "white";
}
}
var element = document.getElementsByTagName('button');
element.addEventListener("mouseover", btn.hover, false);
element.addEventListener("mouseout", btn.out, false);
HTML:
<div>
<button class="accountButton firstButton" id="FacebookExchange"></button>
</div>
Default Style:
.unified_container .row .panel-default #api .localAccount .entry .buttons button {
float: left;
background-image: none;
background-color: #f4f4f4;
border-radius: 0.2rem;
cursor: pointer;
display: inline-block;
font-size: 1em;
font-weight: 400;
height: inherit;
line-height: 1.3333333;
margin-top: 3rem;
margin-right: 0px;
margin-left: 0px;
padding: 10px 16px;
text-align: center;
touch-action: manipulation;
user-select: none;
vertical-align: middle;
white-space: nowrap;
width: inherit;
-moz-user-select: none;
-ms-touch-action: manipulation;
-ms-user-select: none;
-webkit-user-select: none;
color: #000;
width: 100%;
}
.unified_container .row .panel-default #api .localAccount .entry .buttons button:hover {
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
background-color: #d40000;
color: #fff;
}

我得到的错误消息";element.addEventListener不是一个函数;。

如何更改按钮悬停颜色?

PS我不能在按钮中编写内联css、javascript或html,因为按钮是由应用程序动态创建的。

出现此错误的原因是document.getElementsByTagName('button')返回了一个元素数组,该数组的标记名为按钮,因此您的变量元素是一个数组。若要解决此错误,您需要确定此数组中实际有兴趣向其中添加侦听器的元素。例如,如果它是第一个元素,那么您的代码应该看起来像:

element[0].addEventListener("mouseover", btn.hover, false);
element[0].addEventListener("mouseout", btn.out, false);

如果您希望所有按钮元素都有侦听器,那么您可以使用一个简单的foreach循环或映射。

执行document.getElementsByTagName('button')时,会得到一个节点数组。您需要对列表进行迭代,并在每个列表上添加事件侦听器。

var elements = document.getElementsByTagName('button');
elements.forEach(element => {
element.addEventListener("mouseover", btn.hover, false);
element.addEventListener("mouseout", btn.out, false);
});

最新更新