点击后如何在图像上显示和消失文本。

时间:2018-08-21 12:19:23

标签: javascript jquery html css

我正在寻找代码,

假设手机上有图片。如果单击图像,则出现文本,如果再次单击图像,则文本消失。有人可以给我简单的html,css和javascript代码来实现此功能吗?该图像应该是可恢复的。

请帮助。

1 个答案:

答案 0 :(得分:1)

根据您提供的代码,这是一个解决方案,当使用 JavaScript单击容器时,可以切换 div 的可见性

 <style>
    /* Container holding the image and the text */
    .container {
        position: relative;
    }

    /* Bottom right text */
    .text-block {
        position: absolute;
        width: 70%;
        height: 70%;
        top: 20px;
        left: 20px;
        background-color: black;
        color: white;
        padding-left: 20px;
        padding-right: 20px;
        opacity: 0.7;
    }

    p {opacity: 1;}

    #clickToShow{display:none;} /* to hide by default */
</style>

<script>
    //now the function to toggle visibility
    function clickToShow() {
        var div = document.getElementById("clickToShow");
        div.style.display = div.style.display == "block" ? "none" : "block";
    }
</script>
<!-- notice onclick="clickToShow()" this is how you call JS method-->
<div class="container" style="cursor:pointer;" onclick="clickToShow();">
    <img src="https://www.w3schools.com/howto/img_nature_wide.jpg" alt="Norway" style="width:100%; height: 70%;">
    <div class="text-block" id="clickToShow"> 
        <h4>Nature</h4>
        <p>What a beautiful sunrise!</p>
    </div>
</div>

这里是一个小提琴,表明它有效:

https://jsfiddle.net/3e8pnLd4/8/

相关问题