gpt4 book ai didi

javascript - 如何检测在javascript中单击了哪个按钮?

转载 作者:行者123 更新时间:2023-11-28 04:48:18 26 4
gpt4 key购买 nike

我正在尝试弄清楚如何在单击我的函数时携带按钮的 ID。 1 个函数在鼠标悬停时更改颜色,一个函数在鼠标移开时将其更改回原始颜色。我知道我可以在 css 中简单地做到这一点,但我只想学习如何在 javascript 中做到这一点。提前致谢。下面是我的代码。

  var buttonClass = this.className();
// document.getElementById("mainTitle");
this.style.backgroundColor="#000000";
this.style.color="#ffffff";
this.style.cursor = "pointer";
}

function defaultColor() {
var buttonClasss = this.getElementById();
//document.getElementById("addList");
this.style.backgroundColor = "#ffffff";
this.style.color = "#000000";
this.style.cursor = "pointer";
}


//event listener for Change Title button
document.getElementById("mainTitle").addEventListener("mouseover", changeColor);
document.getElementById("mainTitle").addEventListener("mouseout", defaultColor);
document.getElementById("mainTitle").addEventListener("click", changeTitle);
//event listener for change title ends here

//event listener for add listing
document.getElementById("addList").addEventListener("mouseover", changeColor);
document.getElementById("addList").addEventListener("mouseout", defaultColor);
document.getElementById("addList").addEventListener("click", addListing);
//event listener for add listing ends here
#mainTitle {
border:1px solid #ff33f4;
float:left;
clear:both;
font-family:arial;
font-weight:bold;
font-size:20px;
border-radius:50px;
background-color:#ff33ff;
width:200px;
height:35px;
text-align:center;
padding-top:20px;
padding-bottom:10px;
cursor:pointer;
}

#addList {
border:1px solid #ff33f4;
float:right;
font-family:arial;
font-weight:bold;
font-size:20px;
border-radius:50px;
background-color:#ff33ff;
width:200px;
height:35px;
text-align:center;
padding-top:20px;
padding-bottom:10px;
cursor:pointer;
}

#main {
clear:both;
margin-top:120px;
}
 
<div id="mainTitle" class="changeTitle">Change Title</div>
<div id="addList" class="addList">Add List</div>

最佳答案

每个注册的事件都会带有参数 Event .

function defaultColor(e) {
// ^ argument (Event)

var currentClickedButton = e.currentTarget; // to get the current clicked button
/* Your code here */
}

关于javascript - 如何检测在javascript中单击了哪个按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39483803/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com