javascript - 鼠标悬停时保持工具提示(标题属性)更新

标签 javascript jquery html tooltip title

我想显示自上次重新加载页面以来已经过去了多长时间。

<li id="last-update-title" onmouseover="updateTimeToolTip()">Some Text here</li>

这是我拥有的 updateTimeToolTip() 函数

function updateTimeToolTip() {
    document.getElementById('last-update-title').title = customFormatTimeSecondsAgo(updateTime);
};

function customFormatTimeSecondsAgo(date) {
    var result = Math.floor((new Date() - date) / 1000);
    if (result <= 1) return "Updated: Just now";
    return "Updated: " + result + " seconds ago";
};

这些函数现在可以正常工作来计算时间。当我将鼠标悬停在文本上时,它会显示耗时。然而,当鼠标悬停在标题属性上时,标题属性不会改变,这是正常的,但我认为如果我能让它在鼠标悬停在文本上时不断更新,那就太好了。有什么方法可以在不使用任何外部 JQuery 的情况下实现此目的吗?

谢谢

最佳答案

如果我是你,我不会尝试更新 native 浏览器工具提示,我会尝试像这样更自定义的内容:

  <html>
    <head>
    </head>
    <style>

      #last-update-title{
        position: relative;
        margin-top: 20px;
      }

      #tooltip{
        position: absolute;
        top: -20px;
        display:none;
      }

      #tooltip.show{
        display:inherit;
      }

    </style>
    <body>

      <div id="last-update-title" onmouseover="showToolTip('show');" onmouseout="showToolTip('');">
        Some Text here
        <div id="tooltip"></div>
      </div>

    </body>
    <script type="text/javascript">

      function showToolTip(show){
        document.getElementById('tooltip').className = show;
      }

      var startDate = new Date();
      setInterval(function(){
          document.getElementById('tooltip').innerHTML = customFormatTimeSecondsAgo(startDate);
      }, 1000)

      function customFormatTimeSecondsAgo(date) {
          var result = Math.floor((new Date() - date) / 1000);
          if (result <= 1) return "Updated: Just now";

          return "Updated: " + result + " seconds ago";
      };


    </script>
  </html>

这可以避免不同浏览器如何呈现工具提示的问题,并且还可以解决工具提示未按您希望的方式动态更新的问题。

关于javascript - 鼠标悬停时保持工具提示(标题属性)更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23549625/

相关文章:

javascript - 在 onload 函数中设置 Canvas 背景不起作用

javascript - 如何用纯 JavaScript 重写这个 jQuery 搜索过滤功能?

javascript - 按浏览器后退按钮但不工作时尝试重定向到某个页面

jquery - 基于 Geoip 隐藏多个元素

javascript - 定期更改 css 属性并将该值作为文本添加到 div 中

javascript - 检测 jQuery 对象

javascript - 为了使用 Gulp 在我的项目中使用 ES6 样式导入,我需要哪些工具?

ajax - 我可以将自定义错误从 JsonResult 返回到 jQuery ajax 错误方法吗?

jquery - 使用 ':active' 选择器后如何防止调用我的 css 动画?

javascript - 如何在 Adob​​e Brackets IDE 中链接外部 javascript 文件?