当用户单击链接/ onClick时,我想更改链接的BG颜色。这是我目前正在处理的代码;
<a href="javascript:void(0);" onclick="myFunction()" class="dropbtn" id="dropbtn">Link Drop Down</a>
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
document.getElementById("dropbtn").onclick = function()
{
this.style.background = '#FFF';
}
}
但这没有用,我不确定为什么。
最佳答案
<a href="javascript:void(0);" class="dropbtn" id="dropbtn">Link Drop Down</a>
function myFunction() {
document.getElementById("dropbtn").onclick = function(event) {
var drop_down = document.getElementById("myDropdown");
if (!drop_down.classList.contains('show')) {
drop_down.classList.add('show');
this.style.background = '#FFF';
}
else {
drop_down.classList.remove('show');
this.style.background = '';
}
return true;
}
}
myFunction();
基本上,您必须安装
onclick
事件处理程序(请参见https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers),该处理程序将接收带有事件信息的event
参数。它里面的this
实际上指向id = dropbtn
的元素,因此您可以像在问题中一样直接引用它,也可以获取event.target
上的引用。编辑
其实我错了,很抱歉,
this
确实指向单击的元素。修正了答案。关于javascript - 更改链接BG颜色onClick,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61356609/