当我尝试使用输入标签更改div的颜色时,我遇到了一些问题。如果div位于输入的同一部分,则它可以完美运行。但是,如果我试图将div放在页脚中,例如,停止工作。
HTML:
<section>
<input id="select1" name="test" type="radio" checked />
<label for="select1">Red</label>
<input id="select2" name="test" type="radio" />
<label for="select2">Green</label>
<input id="select3" name="test" type="radio" />
<label for="select3">Blue</label>
</section>
<footer>
<div class="colorDiv"></div>
</footer>
CSS:
.colorDiv{
width:50px;
height:50px;
background-color:red;
}
#select2:checked ~ .colorDiv{
background-color:green;
}
#select3:checked ~ .colorDiv{
background-color:blue;
}
以下是一个示例:http://jsfiddle.net/cqscc48g
有什么方法可以达到这个目的吗?
由于
答案 0 :(得分:3)
Css是级联渲染器。所以它遵循DOM元素的结构。因此,您只能关联作为后代的元素,或者至少跟随兄弟姐妹。
您有两种选择:
1 - 调整HTML:
您甚至不需要将div放在输入节中。但至少,你必须让section
的输入成为“侄子”选择器。 (当然这个面额不存在;))
<input id="select1" name="test" type="radio" checked />
<label for="select1">Red</label>
<input id="select2" name="test" type="radio" />
<label for="select2">Green</label>
<input id="select3" name="test" type="radio" />
<label for="select3">Blue</label>
<footer>
<div class="colorDiv"></div>
</footer>
然后你可以选择:
#select2:checked ~ footer .colorDiv{
background-color:green;
}
#select3:checked ~ footer .colorDiv{
background-color:blue;
}
2 - 使用Javascript方法:
如果您非常喜欢HTML结构,那么您必须使用Javascript。你可以把它变得更加清晰,但只是一个例子:
function ChangeColor(color) {
var clrDiv = document.getElementsByClassName("colorDiv")[0];
clrDiv.style.backgroundColor = color;
}
document.getElementById("select1").onclick = function() { ChangeColor(""); }
document.getElementById("select2").onclick = function() { ChangeColor("green"); }
document.getElementById("select3").onclick = function() { ChangeColor("blue"); }
答案 1 :(得分:1)
更改标记并在代码中查看注释
<section>
<input id="select1" name="test" type="radio" checked />
<label for="select1">Red</label>
<input id="select2" name="test" type="radio" />
<label for="select2">Green</label>
<input id="select3" name="test" type="radio" />
<label for="select3">Blue</label>
<div class="colorDiv"></div> <!-- this should be adjacent as per your css selectors -->
</section>
答案 2 :(得分:-1)
如果你想在某个div里面点击并将鼠标悬停在任何身体div上,而不是在顶部外面设置输入..
<style>
input[type=checkbox] {
display:none;
}
input[type=checkbox]:checked ~ div.content{
display:none;
}
</style>
<input type="checkbox" id="toogle-content"/>
<div>
<label for="toogle-content" id="toogle-content">CLICK ME!</label>
</div>
<div class="content">
I can toggle now ;)
</div>
答案 3 :(得分:-2)
每.change()
使用input
。在更改后,点击已点击的输入id
,然后更改div