HTML 按钮点击变红,单选效果示例
<!DOCTYPE html>
<html>
<head>
<title>按钮点击变红,单选效果</title>
<style type="text/css">
button {
background-color: #4CAF50;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
<pre><code> button.red {
background-color: red;
}
</style>
<script type="text/javascript">
function changeColor(btn) {
var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
if (buttons[i] == btn) {
buttons[i].classList.add('red');
} else {
buttons[i].classList.remove('red');
}
}
}
</script>
</code></pre>
</head>
<body>
<button onclick="changeColor(this)">按钮1</button>
<button onclick="changeColor(this)">按钮2</button>
<button onclick="changeColor(this)">按钮3</button>
<button onclick="changeColor(this)">按钮4</button>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/nek3 著作权归作者所有。请勿转载和采集!