简体   繁体   中英

display an image only when button is clicked

Just beginning to learn HTML & Javascript. I have the following code, which works. however, because I have have an img tag in my body it is trying to show a place holder for an image before I click the button. How can I stop this.

<!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>

Best wishes.

Use display property in css, try this:

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>

Add style "display:none" to picture tag

<img id="bigpic" src="bigpic" style="display:none;"/>

And in function picture change it for show image

document.getElementById('bigpic').style.display='block';

There is demo: http://jsfiddle.net/eX5kx/

I like shin solution, i would do the same thing myself. However theres a lot of way to do that, another option is to put a tiny trasparent image as default and then replace like you did to the other one. like this:

<!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>

this way no css is needed but like i said before i prefer Shin's solution.

there is a lot of way to fix that .

-remove border around the img tag img{border:none}

-use div and background-image , change the background-image to the var pic.

document.getElementById('divtag').backgroundImage = pic;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM