这是我第一次真正深入了解javascript。我已经花了好几个小时没有找到解决方案(虽然我学到了很多东西)。
<script type="text/javascript">
function changeClass(){
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (currentClass == "switch switch-blue") {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
}
window.onload = function()
{
document.getElementById("switcher").addEventListener( 'click' , changeClass );
}
</script>
这是HTML:
<div class="switch switch-blue" id="switcher">
<input type="radio" class="switch-input" name="resp" value="1" id="respyes" checked>
<label for="respyes" class="switch-label">YES</label>
<input type="radio" class="switch-input" name="resp" value="2" id="respno">
<label for="respno" class="switch-label">NO</label>
</div>
默认为蓝色背景。如果他们选择“否”,我希望它为红色,如果他们点击“是”,则返回蓝色,这些都在css中。如果我手动将类从switch-blue更改为switch-red,则可以正常工作。现在它什么也没做。
谢谢!
答案 0 :(得分:1)
这里的问题是当内部元素点击事件冒泡时事件传播,所以它导致调用你的函数两次更改类然后还原所以尝试:
function changeClass(event) {
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (currentClass == "switch switch-blue") {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
if (window.event != undefined) window.event.cancelBubble = true;
event.stopPropagation();
}
window.onload = function () {
document.getElementById("switcher").addEventListener('click', changeClass);
}
event.stopPropagation();
将停止此冒泡并使用IE window.event.cancelBubble = true;
但是这不会保证单击按钮单击时类的更改,因为事件绑定到父div,因此在任何地方点击div都会触发事件,所以尝试在单选按钮上绑定事件:
function changeClass(clickedItem) {
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (clickedItem == 1) {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
}
window.onload = function () {
var yes = document.getElementById('respyes');
var no = document.getElementById('respno');
yes.onclick = function () {
changeClass(2)
};
no.onclick = function () {
changeClass(1)
};
}
答案 1 :(得分:0)
当你添加css类时,它看起来工作正常。
这是demo。我想你错过了风格。 将样式添加到您的头部,看看它是否适合您。
<style>
.switch-blue{
background:blue;
color:#fff;
}
.switch-red{
background:red;
color:#fff;
}</style>
随意根据需要更改样式。
修改强>
我只是注意到你有事件监听器附加到div而不是单选按钮。单击div而不是按钮时,这将更改背景。请参阅此updated fiddle。
答案 2 :(得分:0)
function changeClass(elem){
var currentClass = elem.className, blueClass = "switch switch-blue",
redClass= "switch switch-red"
elem.className = (currentClass == blueClass) ? redClass:blueClass;
}
window.onload = function()
{
document.getElementById("switcher").onclick = function(){
changeClass(this);
};
}
JS小提琴: http://jsfiddle.net/dYt8v/