所以,这就是我要做的事情...我想创建一个清单,当选中一个复选框时,会出现相应的图像(默认情况下,每个图像都设置为隐藏)。以下是部分有效的代码:
http://jsfiddle.net/rpt8ck6L/1/
HTML /使用Javascript:
<script>
function toggleVisibility(id) {
var el = document.getElementById(id);
if (el.style.visibility == "visible") {
el.style.visibility = "hidden";
} else {
el.style.visibility = "visible";
}
}
</script>
<label for="001">001</label>
<input type="checkbox" id="001" onChange="toggleVisibility('img001');" />
<br/>
<label for="002">002</label>
<input type="checkbox" id="002" onChange="toggleVisibility('img002');" />
<hr/>
<div class="testclass">
<img id="img001" src="http://tinyurl.com/n6amvuw" width="200" height="200" style="visibility:hidden" />
<img id="img002" src="http://tinyurl.com/mm297df" width="200" height="200" style="visibility:hidden" />
</div>
CSS:
.testclass {
border: 1px solid #000;
position: relative;
}
.img001 {
border: 1px solid #f00;
display: block;
position: relative;
z-index: 2;
}
.img002 {
border: 1px solid #0f0;
display: block;
position: relative;
z-index: 1;
top: -12px;
left: 12px;
}
但是,我还希望图像彼此重叠,这样如果检查了两个,那么第二个将出现在顶部。为了让图像重叠,我被告知我必须使用CSS样式(使用z-index)和图像CLASSES而不是ID。
因此,我只是将代码更改为使用className而不是ID:
HTML /使用Javascript:
<script>
function toggleVisibility(className) {
var el = document.getElementByClassName(className);
if (el.style.visibility == "visible") {
el.style.visibility = "hidden";
} else {
el.style.visibility = "visible";
}
}
</script>
<label for="001">001</label>
<input type="checkbox" id="001" onChange="toggleVisibility('img001');" />
<br/>
<label for="002">002</label>
<input type="checkbox" id="002" onChange="toggleVisibility('img002');" />
<hr/>
<div class="testclass">
<img class="img001" src="http://tinyurl.com/n6amvuw" width="200" height="200" style="visibility:hidden" />
<img class="img002" src="http://tinyurl.com/mm297df" width="200" height="200" style="visibility:hidden" />
</div>
CSS:
.testclass {
border: 1px solid #000;
position: relative;
}
.img001 {
border: 1px solid #f00;
display: block;
position: relative;
z-index: 2;
}
.img002 {
border: 1px solid #0f0;
display: block;
position: relative;
z-index: 1;
top: -12px;
left: 12px;
}
然而,这不起作用(当复选框被选中时,图像甚至不会出现)...我假设问题与使用className有关?如果有人可以从第二个链接获取代码(这样图像将重叠并在选中时显示/消失),那就太棒了。非常感谢你。
答案 0 :(得分:0)
您只需使用排名absolute
即可解决问题。你的原始JavaScript很好。
工作小提琴:http://jsfiddle.net/rpt8ck6L/2/
CSS:
#img001, #img002 {
width:200px;
height:200px;
position:absolute;
top:80px;
left:0px;
z-index:1;
}
#image002 {
z-index: 2
}