![](/img/trans.png)
[英]How to change the color of the div depending on which button i click ? ( javascript/css/html ONLY no library)
[英]change background color of div on button click using HTML/CSS or javascript
我有4個div,每個div都有幾個控件和一個按鈕。
如何根據div中的按鈕單擊將div的背景色更改為灰色。
首先需要找到所有按鈕元素。
var buttons = document.getElementsByTagName("button");
接下來,遍歷按鈕元素,並將事件偵聽器添加到每個按鈕。
單擊按鈕后,將父級的背景顏色更改為灰色。
this.parentElement.style.backgroundColor = "grey";
var buttons = document.getElementsByTagName("button"); for(var i=0; i<buttons.length; i++) { buttons[i].addEventListener("click",function(e) { this.parentElement.style.backgroundColor = "gray"; }) }
hr{ margin:0px; border:none; height:1px; background-color:gray; }
<div> I will change color when you click the button. <button>Click Me</button> </div> <hr/> <div> I will change color too. <button>Click Me</button> </div> <hr/> <div> What about me? <button>Click Me</button> </div>
好吧,這是您的問題的非引導解決方案:
HTML:
<div id="1">
<button onclick="button = 1; changecolour();">Click Me</button>
</div>
<div id="2">
<button onclick="button = 2; changecolour();">Click Me</button>
</div>
<div id="3">
<button onclick="button = 3; changecolour();">Click Me</button>
</div>
CSS(可選((用於演示))):
div {
height: 150%;
width: 30%;
display: inline-block;
background-color: lightgreen;
-webkit-box-shadow: 0 3px 4px black;
-moz-box-shadow: 0 3px 4px black;
box-shadow: 0 3px 4px black;
text-align: center;
padding: 5px;
}
Javascript:
var button = "";
function changecolour() {
console.log(button);
document.getElementById(button).style.backgroundColor = "lightgray";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.