如何使用javascript在onClick上显示图片

时间:2014-05-08 16:17:29

标签: javascript html onclick

这是html

<div id="first_caption">
    <p style="float: left; clear: left">
        <a id="light_on" href="#" onclick="myClick()">
            <img id="light_img" src="http://www.ottawaskeptics.org/images/stories/lightbulb.jpg" height="50" width="50">
        </a>
        How can you stay healthy and do more of the things you love? Click the light  bulb to find out how.
    </p><br><br><br>
</div>
<div id="heading1">
</div>

这是javaScript

<script>
    function myClick(){
        text = "<b><i><br><br>You can save a ton of money by drinking tap or filtered water,  instead of wasting hundreds of dollars on bottled water. Did you know the average person spends $100+ per person every year! The good thing is its not your fault; many people are inticed by clever advertising, and thinking it has neutrisional values that other water does not contain. The truth is Big companies like Nestle and Coca'cola are simply profiting off making you think youre making a healthy choice. Bottled water is only tested once a weak for contamination and germs, and is no better than your average tap water. Honestly, if you really wanted to make a healthier decision try filtered water. You could argue that you still have a water bill dont you? well, according to STATISTIC BRAIN,'the total cost of a monthly water bill if tap cost as much as the cheapest watter bottle would be $9000!'  </i></b>";
        document.getElementById('heading1').innerHTML = document.getElementById('heading1').innerHTML + text;
        document.getElementById("heading1").style.textAlign="left";
        document.getElementById("heading1").style.marginLeft="20px";
    }
</script>

基本上点击灯泡后,图片下方会出现一些文字。我想知道如何使用相同的方法来改变图片。

3 个答案:

答案 0 :(得分:0)

更改“文字”内容,不要追加,只需覆盖:

 <script>
    function myClick(){
    text = "<img src='http://www.online-image-editor.com/styles/2013/images/example_image.png'";
    document.getElementById('heading1').innerHTML = text;
    }

 </script>

答案 1 :(得分:0)

你可以在html中用style =&#34; display:none;&#34;创建一个img元素。然后获取此元素并使用display:block;设置新样式;在myClick()函数内部

答案 2 :(得分:0)

您可以将图片添加到HTML代码中,并将display属性设置为none,然后使用javascript进行更改。

HTML

<div id="first_caption">
    <p style="float: left; clear: left">
        <a id="light_on" href="#" onclick="myClick()">
            <img id="light_img" src="http://www.ottawaskeptics.org/images/stories/lightbulb.jpg" height="50" width="50" />

        </a>
        How can you stay healthy and do more of the things you love? Click the light  bulb to find out how.
    </p><br><br><br>
</div>
<div id="heading1">
    <img id="myNewImage" src="" /> <!-- your new image -->
</div>

CSS

#myNewImage { display:none; }

的Javascript

function myClick() {
    document.getElementById("myNewImage").style.display = "block";
}