单击更改链接背景颜色



我想在用户单击链接时更改链接的BG颜色/onClick。这是我目前正在编写的代码;

<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确实指向点击的元素。修正了答案。

试试这个:

<a href="javascript:void(0);" onclick="myFunction(e)" class="dropbtn" id="dropbtn">Link Drop Down</a>

function myFunction(e) {
document.getElementById("myDropdown").classList.toggle("show");
e.target.style.background = '#FFF';
}

最新更新