方法一:
把图片的display设为none,触发点击事件时,display变为block
<style> img { 400px;height: 300px; display: none; } </style> <body> <input id = "btn" type="button" value="clickme"> <img src="images/1.jpg" id="pic"> <script> var btn = document.getElementById("btn"); var pic = document.getElementById("pic"); btn.onclick= function (){ pic.style.display = "block"; } </script>
方法二:
在html中不加图片,js触发点击事件时添加图片
<style> input{ display: block; } </style> <body> <input id = "btn" type="button" value="clickme"> <img src="" id="pic"> <script> var btn = document.getElementById("btn"); var pic = document.getElementById("pic"); btn.onclick= function (){ pic.src="images/1.jpg"; pic.style.width="400px"; pic.style.height="300px"; } </script>
方法三:
更换class名,先给img用使图片隐藏的样式,触发点击事件,更换为显示图片的属性。
<style> input{ display: block; } .pic{ 400px; height: 300px; display: block; } .hide{ 400px;height: 300px; display: none; } </style> <body> <input id = "btn" type="button" value="clickme"> <img src="images/1.jpg" id="pic" class="hide" class="pic" > <script> var btn = document.getElementById("btn"); var pic = document.getElementById("pic"); btn.onclick=function(){ pic.className="pic"; } </script>