html 如何使用javascript在单击时显示图片

8wtpewkr  于 2022-11-20  发布在  Java
关注(0)|答案(3)|浏览(186)

这里是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>

基本上在我点击灯泡后,一些文字会出现在图片下面。我想知道使用同样的方法,我如何才能让一张图片代替出现。

r7s23pms

r7s23pms1#

更改“文本”内容,并且不追加,只覆盖:

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

 </script>
31moq8wy

31moq8wy2#

您可以使用style=“display:none;”,然后获取此元素并使用display设置新样式:块;在myClick()函数内部

laximzn5

laximzn53#

您可以将图像添加到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";
}

相关问题