【问题标题】:Display image legend on hover (not as tooltip) using innerHTML?使用innerHTML在悬停时显示图像图例(不是工具提示)?
【发布时间】:2018-07-09 18:04:58
【问题描述】:

我有一个包含许多图像的网页,每个图像都有一个title 属性。当我将鼠标悬停在图像上时,我希望 title 文本显示在我创建的单独 legend 元素中(不是作为微小的悬停工具提示)。我有一个工作正常的mouseover 函数 - 即当我将鼠标悬停在图像上时,图例会更改值。但我希望该值是单个图像的 title 文本 - 我不知道如何访问。我试过…innerHTML = this.title,这显然是不正确的。

[图片的数量很大而且不断变化(就像相册一样),所以我不能为每个<img> 标签添加单独的代码。我可以使用alt 或任何其他<img> 属性来完成这项工作。我也不喜欢innerHTML 方法,但我希望有一些简单的代码来解决这个问题!]

请帮忙?谢谢! (仅供参考,我是新手编码员。)

<!DOCTYPE html>
<html>
<body>

  <h1 id="legend">title appears here</h1>

  <div>
    <img src="image1.jpg" onmouseover="mouseOver()" title="Breakfast">
    <img src="image2.jpg" onmouseover="mouseOver()" title="Lunch">
    <img src="image3.jpg" onmouseover="mouseOver()" title="Dinner">
  </div>

  <script>
    function mouseOver() {
        document.getElementById("legend").innerHTML = this.title;
    }
  </script>

</body>
</html>

【问题讨论】:

    标签: javascript html image hover innerhtml


    【解决方案1】:

    您似乎正在尝试使用this.title 来表示不同的图像?如果您希望他们的标题出现在&lt;h1&gt; 标记中,您需要将信息传递给如下所示的函数。

     <h1 id="legend">title appears here</h1>
    
      <div>
        <img src="image1.jpg" onmouseover="mouseOver(this)" title="Breakfast">
        <img src="image2.jpg" onmouseover="mouseOver(this)" title="Lunch">
        <img src="image3.jpg" onmouseover="mouseOver(this)" title="Dinner">
      </div>
    
      <script>
        function mouseOver(x) {
            document.getElementById("legend").innerHTML = x.title;
        }
      </script>

    【讨论】:

      【解决方案2】:

      我想它很有帮助。

      但我使用 Jquery 只需在您的&lt;head&gt; 中调用此代码

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      
       <!DOCTYPE html>
          <html>
          <head>
          <script 
          src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
          </script>
          </head>
          <body>
      
            <h1 id="legend">title appears here</h1>
      
            <div>
              <img src="image1.jpg" class="class_of_div" title="Breakfast">
              <img src="image2.jpg" class="class_of_div" title="Lunch">
              <img src="image3.jpg" class="class_of_div" title="Dinner">
            </div>
      
            <script>
              $(document).on('mouseover', '.class_of_div', function () {
                  var thiss=$(this);
                  $('#legend').text(thiss.attr('title'));
              });
            </script>
      
          </body>
          </html>
      

      【讨论】:

        猜你喜欢
        • 2021-10-02
        • 1970-01-01
        • 2015-12-07
        • 1970-01-01
        • 2022-11-18
        • 2022-09-29
        • 2017-01-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多