首页 > 解决方案 > 点击后如何使文本在图像上出现和消失。

问题描述

我正在寻找一个代码,

假设手机上有一张图片。如果我们点击图像文本会出现,如果我们再次点击图像,文本就会消失。有人可以给我这个功能的简单 html、css 和 javascript 代码吗?图像应该是响应式的。

请帮忙。

标签: javascriptjqueryhtmlcss

解决方案


根据您提供的代码,这是一个解决方案,允许在使用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/


推荐阅读