我有4个简单的按钮。我怎么能设置它们,所以当点击其中一个时它有一些属性改变并保持变化?当另外一个按钮被点击时,它会改变相同但它会将第一个按钮的属性恢复为“正常”?基本上,它们是导航按钮,我希望它们显示您所在的页面的哪个部分。提前谢谢。
答案 0 :(得分:2)
我为点击制作了一个示例并仅更改了背景颜色:
<强> CSS 强>
.beforeClick {
background-color:#EEE;
}
<强>的JavaScript 强>
$(document).ready(function (){
$('.beforeClick').click(function (){
$('.beforeClick').css('background-color',"#EEE");
$(this).css('background-color',"#555");
});
});
<强> HTML 强>
<button class="beforeClick">btn1</button>
<button class="beforeClick">btn2</button>
<button class="beforeClick">btn3</button>
<button class="beforeClick">btn4</button>
<button class="beforeClick">btn5</button>
(你需要jQuery)
这是DEMO
答案 1 :(得分:2)
利用课程来切换按钮的状态。类似的东西:
<div class="button">PRESS</div>
....
<div class="button">PRESS</div>
只需要另一个.selected
类,你可以通过几行vanilla JavaScript来覆盖你的场景:
var buttons = document.getElementsByClassName('button');
for (var i = 0; i < buttons.length; i++) { //loop through all buttons
buttons[i].addEventListener('click', function() {
if (document.getElementsByClassName('selected').length) { //check if we already have a selected element
document.getElementsByClassName('selected')[0].className = document.getElementsByClassName('selected')[0].className.replace(/(?:^|\s)selected(?!\S)/g, ''); //remove selected class from "old" element
}
this.className += ' selected'; //add selected class to element that has been clicked / called the handler
});
}
答案 2 :(得分:1)
我要做的是编写一个javascript函数,例如:
<script type='text/javascript'>
function toggle(btn)
{
var btnArray = document.getElementsByClassName('button');
for(i = 0; i < btnArray.length; i++)
{
if(btn == btnArray[i])
{
//the button is the button which is clicked
if(!btn.classList.contains("clicked"))
{
btn.className += " clicked";
}
}
else
{
//remove class clicked, just reset the classname
btnArray[i].className = "button";
}
}
}
</script>
<button class="button" onclick="toggle(this);">btn1</button>
<button class="button" onclick="toggle(this);">btn2</button>
<button class="button" onclick="toggle(this);">btn3</button>
您可以在css中添加“clicked”类的说明。
.clicked{
background-color: red;
}
(我在Chromium中测试了这段代码,但它确实有效。)