你好,我是一个相对新手,当谈到网页设计一般,我有一个地狱的时间试图找出如何切换一个png图像从隐藏到可见。实际上,我想发生的是有一个基本的图像,总是显示在网页上,并能够使用复选框切换或关闭特定的png图像。我确信这是一件非常简单的事情,但在花了半天时间搜索谷歌后,我对自己有了更好的想法,并决定寻求一些帮助。
下面是我使用的HTML、CSS和JavaScript:
<!DOCTYPE html>
<html>
<head>
<!---->
<style>
.buttonBar {
width:64%;
margin: 2% 17%;
padding: 1%;
border: 2px solid #44506e;
border-radius: 5px;
background-color: #c1baa9;
}
.pngCake {
position: relative;
width:60%;
margin-left: 17%;
padding: 3%;
border: 2px solid #44506e;
border-radius: 5px;
background-color: #c1baa9;
}
#base {
position: relative;
top: 0;
left: 0;
}
.pngCake #png, .pngCake #png1 {
position: absolute;
top: 0;
left: 0;
visibility: hidden;
}
</style>
<title>Image Cake</title>
</head>
<body>
<div class="buttonBar">
<label class="cb">
<input type="checkbox" onclick="pngLayer()">
<span class="cm"></span>
PNG</label>
<!-- Printer Checkbox -->
<label class="cb">
<input type="checkbox" onclick="pngLayer1()">
<span class="cm"></span>
PNG 1</label>
</div>
<div class="pngCake">
<img id="base" src="base.png"></img>
<img id="png" src="png.png"></img>
<img id="png1" src="png1.png">
</div>
<script>
function pngLayer() {
var portCheck = document.getElementById("png");
portCheck.style.visibility = "visible";
}
function pngLayer1() {
var portCheck = document.getElementById("png1");
portCheck.style.visibility = "visible";
}
</script>
</body>
</html>
在JavaScript中,我尝试过使用toggle命令来提取一个CSS的副本,并将可见性设置为visible。此外,我还尝试过使用if else语句来检查png的可见性是否设置为hidden vs visible,并更改它。在每种情况下,结果都不起作用。
if(document.getelementbyid("png").style.visibility == "hidden") {
document.getelementbyid("png").style.visibility == "visible"
}
else {
document.getelementbyid("png").style.visibility == "hidden
}
一个一个二个一个一个一个三个一个一个一个一个一个四个一个
3条答案
按热度按时间4zcjmb1e1#
看这些,代码中的注解解释了它是如何工作的。
(我只复制了我修改的部分)
event.target.checked
-根据复选框的状态返回true(选中)或false(未选中)。Ternary Operator Docs
希望这个有用。
pzfprimi2#
我看了一下你的脚本,但它是一个绝对混乱,所以它会采取少得多的时间从零开始创建这样一个简单的程序。
您只需要一个图像标记,并且只需在用户单击选择控件时更改src属性。
图像选择控件最好用单选按钮来表示,单选按钮一次只允许一个选择,因为没有理由让三个图像相互堆叠。
好的,这是脚本......替换我在注解中指出的图像路径,并继续练习。
46scxncf3#
CodePen
在这个CodePen中,我认为这可能是解决这个问题的好方法,请在尝试之前好好给予一下,看看它是否符合您的用例。
HTML部分几乎是您需要的任何部分,我只是放置了一个 Package 器,这样我就可以更好地为测试设置样式。
在JS部分,有一个字符串数组,我Map它们来构建我的
imgs
这是您可以放置URL的位置。
在它的正下方,Map
images
并创建img
和checkbox
(如果您需要在其他地方创建复选框,您可以创建一个不同的函数来附加它,该函数与我现有的函数不同)然后是
onToggle
函数,我通过id
(我在创建它时设置的)获取img
,然后检查类hidden
是否在类列表中,如果没有,我添加它,否则我删除它,切换图像可见性。还有中央情报局
我是这样做的,但老实说,如果你愿意,你可以使用
inline styles
。作为开发人员,既然你要加载多个图像,我会尽量减少手动添加,只需要在它们之间循环。但是你也可以手动添加,调用函数
onToggle
,并在每个checkbox
onclick
中传递id
。如下所示: