首页 > 解决方案 > 悬停时显示工具提示的 HTML 元素

问题描述

我有几个 HTML 元素需要在悬停时显示工具提示。这些不是传统的 HTML 元素,来自后端生成的脚本,我无权更改。从前端的角度来看,我想知道的是如何在不在 HTML 中声明的情况下显示工具提示。

我尝试使用 Bootstrap 工具提示,但您需要在 HTML 标记中将其声明为标题,所以它没有用。因此,如下面的示例所示,当您将鼠标悬停在包含“应该”的“操作”元素上时,我需要一些文本说“操作”出现在工具提示中。当您将鼠标悬停在“量词”元素中包含的文本“近似数量”上时,同样会应用 - 应该显示“量词”一词。希望这是有道理的。

 <body>
 One string that <Action>should</Action> work is 
 <Quantifier>approximate number of</Quantifier> other things.

 <script>
  $(document).ready(function(){
   $("Action").hover(function(){

   });
   $("Quantifier").hover(function(){

    });
  });
 </script>
 <body>

到目前为止还没有定论,因为我只能更改 CSS 值而不是工具提示文本。

标签: javascriptjqueryhtmlcsstwitter-bootstrap

解决方案


您可以尝试更新title这些元素的属性。需要注意的一点是,HTML 标记在编译时会以小写形式出现。

$(document).ready(function() {
  var style = document.createElement('style');
  style.type = 'text/css';
  $('head')[0].appendChild(style);
  style.innerHTML = 
    `action, quantifier {
      position: relative;
      display: inline-block;
      margin-top: 20px;
    }

    action[title]:hover:after, quantifier[title]:hover:after {
      content: attr(title);  
      position: absolute;
      top: -100%;
      left: 0;
    }

    action[title]:hover:after {
      color: red;
      border: solid 1px black;
    }

    quantifier[title]:hover:after {
      color: blue;
      border: solid 1px black;
    }`;

  $('action')[0].title = 'Action';
  $('quantifier')[0].title = 'Quantifier';

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
One string that <Action>should</Action> work is 
<Quantifier>approximate number of</Quantifier> other things.
</body>


推荐阅读