相对于鼠标指针的 HTML 工具提示位置 [英] HTML-Tooltip position relative to mouse pointer

查看:49
本文介绍了相对于鼠标指针的 HTML 工具提示位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将工具提示对齐自然样式:鼠标指针的右下角?

How to align the tooltip the natural style: right bottom of the mouse pointer?

<!DOCTYPE html>
<html>
<head>
  <title>Tooltip with Image</title>
  <meta charset="UTF-8">
  <style type="text/css">
    .tooltip {
        text-decoration:none;
        position:relative;
    }
     .tooltip span {
        display:none;
    }
     .tooltip span img {
        float:left;
    }
     .tooltip:hover span {
        display:block;
        position:absolute;
        overflow:hidden;
    }
  </style>
</head>
<body>
  <a class="tooltip" href="http://www.google.com/">
    Google
    <span>
      <img alt="" src="http://www.google.com/images/srpr/logo4w.png">
    </span>
  </a>
</body>
</html>

推荐答案

对于默认工具提示行为,只需添加 title 属性.不过这不能包含图像.

For default tooltip behavior simply add the title attribute. This can't contain images though.

<div title="regular tooltip">Hover me</div>

在你澄清这个问题之前,我是用纯 JavaScript 完成的,希望你觉得它有用.图像将弹出并跟随鼠标移动.

Before you clarified the question I did this up in pure JavaScript, hope you find it useful. The image will pop up and follow the mouse.

jsFiddle

JavaScript

var tooltipSpan = document.getElementById('tooltip-span');

window.onmousemove = function (e) {
    var x = e.clientX,
        y = e.clientY;
    tooltipSpan.style.top = (y + 20) + 'px';
    tooltipSpan.style.left = (x + 20) + 'px';
};

CSS

.tooltip span {
    display:none;
}
.tooltip:hover span {
    display:block;
    position:fixed;
    overflow:hidden;
}

扩展多个元素

多元素的一种解决方案是更新所有工具提示 span 并在鼠标移动时将它们设置在光标下.

Extending for multiple elements

One solution for multiple elements is to update all tooltip span's and setting them under the cursor on mouse move.

jsFiddle

var tooltips = document.querySelectorAll('.tooltip span');

window.onmousemove = function (e) {
    var x = (e.clientX + 20) + 'px',
        y = (e.clientY + 20) + 'px';
    for (var i = 0; i < tooltips.length; i++) {
        tooltips[i].style.top = y;
        tooltips[i].style.left = x;
    }
};

这篇关于相对于鼠标指针的 HTML 工具提示位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆