【问题标题】:JavaScript - img caption to appear/disappear onclick eventJavaScript - img 标题出现/消失 onclick 事件
【发布时间】:2022-02-11 19:59:44
【问题描述】:

我需要使用 JS 让图像标题在 1 次鼠标单击时出现并在下次单击时消失。我无法弄清楚为什么当我单击带有 onclick 事件和函数在外部 JS 上使用的图像时没有出现图像标题。抱歉,如果我在问题上犯了任何错误,因为这是我在论坛上的第一篇文章。

HTML

<div id="section1" >
        <h1>Pictures from my vacation</h1>`enter code here`
        <figure style="float: left;" >
            <img src="Photos/p1.jpg" title="Beach" value="hide/show" onclick="showOrHide()">
            <figcaption id="showthis"  style="visibility: hidden;">Waterton Beach</figcaption>
        </figure>
    <p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.                                                                                                                                                                                         
    </p>
</div>

JS

函数 showOrHide() {

if (show=="false") {

document.getElementById("showthis").style.visibility="visible";
show="true";
    
}
else {
//show is true
document.getElementById("showthis").style.visibility="hidden";
show="false";
}

}

【问题讨论】:

  • 你在哪里声明show变量?

标签: javascript html


【解决方案1】:

有几件事可以帮助您顺利上路:

  1. 我不会使用onxyz-attribute-style 事件处理程序。它们只能调用全局函数,向它们传递参数很困难,因为在 HTML 属性中处理 JavaScript 代码中的文本以及其他各种事情。我会使用像addEventListener 这样的现代事件处理。

    但是,如果您确实想为此使用 onclick 属性,我会使用 onclick="showOrHide(this)"this 将引用此点击所在的图像),然后接受 img 参数函数,而不是使用 id 进行查找。

  2. truefalse 等布尔值不要放在引号中。

  3. 您似乎没有在任何地方声明您的 show 变量。

  4. 我会使用一个类而不是直接修改元素的样式。

所以考虑到所有这些:

"use strict";

document.addEventListener("click", event => {
    const img = event.target.closest(".toggle-image");
    if (img && img.nextElementSibling.tagName === "FIGCAPTION") {
        img.nextElementSibling.classList.toggle("hidden");
    }
});
.hidden {
    visibility: hidden;
}
<div id="section1">
    <h1>Pictures from my vacation</h1>`enter code here`
    <figure style="float: left;">
        <img src="Photos/p1.jpg" class="toggle-image" title="Beach" value="hide/show">
        <figcaption class="hidden">Waterton Beach</figcaption>
    </figure>
    <p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.
    </p>
</div>

该代码使用event delegation,方法是将整个文档上的点击挂钩,然后在发生点击时查看点击是否在.image-toggle 元素上(或在冒泡时通过)。如果是,它会查看img 之后的下一个元素,看看它是否是figcaption,如果是,则在元素的class list 元素中toggles 一个hidden 类来显示/隐藏标题。

(这些链接指向 MDN,这是一个很好的网络编程信息资源。)

【讨论】:

  • 谢谢,我是初学者,我的作业需要这个。我还需要了解更多。在这里感谢所有答案。
【解决方案2】:

我改变了一些东西。

html代码:

<div id="section1" >
    <h1>Pictures from my vacation</h1>`enter code here`
    <figure style="float: left;" >
        <img id="myImage" src="https://logowik.com/content/uploads/images/526_liverpoolfc.jpg" title="Beach">
        <figcaption id="showthis"  style="visibility: hidden;">Waterton Beach</figcaption>
    </figure>
<p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.                                                                                                                                                                                         
</p>

我删除了内联 onclick 属性,因为最好在 JS 中添加事件侦听器,如下面的代码所示。 然后使用 JS 添加点击监听器并检查可见性值,然后显示或隐藏它。

JS代码:

const myImage = document.getElementById("myImage")
const caption = document.getElementById("showthis")
myImage.addEventListener("click", () => {
 if(caption.style.visibility == "visible") {
  caption.style.visibility = "hidden"
 } else {
  caption.style.visibility = "visible"
 }

})

这是在做切换功能。如果您希望标题在图像上方,这是 CSS 的问题。

【讨论】:

    【解决方案3】:

    而不是向图像添加点击事件。尝试向图像添加事件侦听器。

    HTML

     <div id="section1">
      <h1>Pictures from my vacation</h1>
      `enter code here`
      <figure style="float: left;">
        <img
          src="https://images.unsplash.com/photo-1644550805208-54b031553153?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1228&q=80"
          title="Beach"
          value="hide/show"
          class="beach-img"
        />
        <figcaption id="showthis" style="visibility: hidden;">
          Waterton Beach
        </figcaption>
      </figure>
      <p>
        Beautiful and Sunny day at Wateron last year. Taking Ferry to explore
        around the late and natural beauty surrounded there. It was a beatiful
        day and beach and small town with full of visitors. Hope to back to this
        beautiful small town on summer break.
      </p>
    </div>
    

    JS

    let show = false;
    const beachImg = document.querySelector(".beach-img")
    beachImg.addEventListener("click", function () {
     if (show === false) {
       console.log("showing");
       document.getElementById("showthis").style.visibility = "visible";
       show = true;
    } else {
       //show is true
       console.log("hiding");
       document.getElementById("showthis").style.visibility = "hidden";
       show = false;
    }
    

    });

    这是working example

    【讨论】:

    • 谢谢,谢谢。如何对 5 个不同的图像使用相同的功能?我该如何循环。
    • 我更新了工作示例以适应您的场景。如果您有任何问题,请告诉我。
    【解决方案4】:

    如果显示/隐藏标题只是您的目标,请尝试此代码。这应该可以。

    <div id="section1" >
       <h1>Pictures from my vacation</h1>
       <figure style="float: left;" >
          <img src="https://picsum.photos/200/300" title="Beach" onclick="showOrHide()">
          <figcaption id="showthis"  style="visibility: hidden;">Waterton Beach</figcaption>
       </figure>
       <p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.                                                                                                                                                                                       
       </p>
    </div>
    

    Javascript函数应该是这样的。

    function showOrHide() {
        const visibility = document.getElementById("showthis").style.visibility;
        if (visibility == "hidden") {
            document.getElementById("showthis").style.visibility = "visible";
        } else {
            document.getElementById("showthis").style.visibility = "hidden";
        }
    }
    

    如果您希望此 javascript 函数处理多个图像,您可以像这样修改该函数。并在 img 标签上的 html 中将事件传递给函数showOrHide(event)

    function showOrHide(e) {
        const img = e.target;
        const figcaption = img.nextElementSibling;
        const visibility = figcaption.style.visibility;
        if (visibility == "hidden") {
            figcaption.style.visibility = "visible";
        } else {
            figcaption.style.visibility = "hidden";
        }
    }
    

    【讨论】:

    • 谢谢,我只是个初学者。如果我想为 5 张图片添加标题,我是否需要 5 个具有不同 ID 的功能,或者我可以使用循环为 5 张图片使用相同的功能?在这种情况下如何使用循环?
    • 那么在这种情况下,您可以使用 event 对象来获取对触发事件的元素的引用,然后您可以找到最近的 figcaption 元素并以与我们类似的方式显示或隐藏它在这个函数中。
    • 检查我对答案所做的编辑。这将处理多个图像。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多