[英]display an image only when button is clicked
刚开始学习HTML和Javascript。 我有以下代码,可以正常工作。 但是,由于我的体内有一个img标签,因此在单击按钮之前,它试图显示图像的占位符。 我该如何制止。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tesco JSONP</title>
<script type="text/javascript">
function picture(){
var pic = "http://img.tesco.com/Groceries/pi/118/5000175411118/IDShot_90x90.jpg"
document.getElementById('bigpic').src = pic.replace('90x90', '225x225');
}
</script>
</head>
<body>
<img id="bigpic" src="bigpic" />
<button onclick="picture()">Enlarge</button>
</body>
</html>
最好的祝愿。
在CSS中使用display
属性,请尝试以下操作:
JavaScript的:
function showPicture() {
var sourceOfPicture = "http://img.tesco.com/Groceries/pi/118/5000175411118/IDShot_90x90.jpg";
var img = document.getElementById('bigpic')
img.src = sourceOfPicture.replace('90x90', '225x225');
img.style.display = "block";
}
HTML:
<img style="display:none;" id="bigpic" src="bigpic" />
<button onclick="showPicture()">Enlarge</button>
在图片标签中添加样式“ display:none”
<img id="bigpic" src="bigpic" style="display:none;"/>
并在功能图片中将其更改为显示图片
document.getElementById('bigpic').style.display='block';
有演示: http : //jsfiddle.net/eX5kx/
我喜欢简单的解决方案,我自己也会做同样的事情。 但是,有很多方法可以执行此操作,另一种方法是将一个小的透明图像作为默认图像,然后像对另一个图像一样进行替换。 像这样:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tesco JSONP</title>
<script type="text/javascript">
function picture(){
var pic = "http://img.tesco.com/Groceries/pi/118/5000175411118/IDShot_90x90.jpg"
document.getElementById('bigpic').src = pic.replace('90x90', '225x225');
}
</script>
</head>
<body>
// tiny trasparent image
<img id="bigpic" src="https://maps.gstatic.com/mapfiles/markers2/dd-via-transparent.png" alt="" />
<button onclick="picture()">Enlarge</button>
</body>
</html>
这样就不需要css了,但是就像我在喜欢Shin的解决方案之前所说的那样。
有很多方法可以解决这个问题。
-删除img标签img{border:none}
周围的img{border:none}
-使用div和background-image,将background-image更改为var pic。
document.getElementById('divtag').backgroundImage = pic;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.