我正在创建一个基于CSS的工具提示,它将在工具提示中包含大量内容,而不是在静态的地方我想知道当你将鼠标悬停在光标上时,有一种简单的方法可以使它跟随光标链接。
以下是基于CSS的工具提示
的示例<div class="couponcode">First Link
<span class="coupontooltip">Content 1</span>
</div>
.couponcode:hover .coupontooltip {
display: block;
}
.coupontooltip {
display: none;
background: #C8C8C8;
margin-left: 28px;
padding: 10px;
position: absolute;
z-index: 1000;
width:200px;
height:100px;
}
答案 0 :(得分:8)
像这样的东西
var tooltip = document.querySelectorAll('.coupontooltip');
document.addEventListener('mousemove', fn, false);
function fn(e) {
for (var i=tooltip.length; i--;) {
tooltip[i].style.left = e.pageX + 'px';
tooltip[i].style.top = e.pageY + 'px';
}
}
答案 1 :(得分:6)
这是一个考虑窗口高度和宽度的版本:
function showTooltip(e) {
var tooltip = e.target.classList.contains("coupontooltip")
? e.target
: e.target.querySelector(":scope .coupontooltip");
tooltip.style.left =
(e.pageX + tooltip.clientWidth + 10 < document.body.clientWidth)
? (e.pageX + 10 + "px")
: (document.body.clientWidth + 5 - tooltip.clientWidth + "px");
tooltip.style.top =
(e.pageY + tooltip.clientHeight + 10 < document.body.clientHeight)
? (e.pageY + 10 + "px")
: (document.body.clientHeight + 5 - tooltip.clientHeight + "px");
}
var tooltips = document.querySelectorAll('.couponcode');
for(var i = 0; i < tooltips.length; i++) {
tooltips[i].addEventListener('mousemove', showTooltip);
}
.couponcode {
color: red;
cursor: pointer;
}
.couponcode:hover .coupontooltip {
display: block;
}
.coupontooltip {
position: absolute;
white-space: nowrap;
display: none;
background: #ffffcc;
border: 1px solid black;
color: black;
padding: 5px;
z-index: 1000;
}
Lorem ipsum dolor sit amet, <span class="couponcode">consectetur
adipiscing<span class="coupontooltip">This is a tooltip</span></span>
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in <span
class="couponcode">reprehenderit<span class="coupontooltip">This is
another tooltip</span></span> in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est <span
class="couponcode">laborum<span class="coupontooltip">This is yet
another tooltip</span></span>.
(另见this Fiddle)