【发布时间】:2017-06-23 17:37:44
【问题描述】:
我创建了自定义工具提示,以在用户将鼠标悬停在“标题”元素上时显示其详细信息。只有一个元素充当工具提示本身,因此即使有多个“标题”元素,工具提示也会跳来跳去,显示当前鼠标悬停的元素的详细信息。
所需行为:工具提示需要在其“标题”元素的中心正上方弹出,以便工具提示底部的箭头与标题元素的中心对齐。
实际行为:工具提示的位置大约偏离 30 像素,这是用户第一次将鼠标悬停在任何给定的“标题”元素上。如果用户将鼠标从元素上移开,然后又回到同一个元素上,那么它将是正确的。请参阅下面的 sn-p 以了解我的意思。
为什么我第一次滚动“标题”元素时工具提示没有正确定位?
另外,如果工具提示中的文本都只包含一行,它似乎工作得很好。
$('.details').hide();
$('.title').mouseenter(function() {
var el = $(this).attr('name'),
eventPos = $('.title[name="' + el + '"]').offset(),
yPos = (eventPos.top - ($('.details').outerHeight() + 5)) + 'px',
xPos = ((eventPos.left + ($('.title[name="' + el + '"]').outerWidth() / 2)) - ($('.details').outerWidth() / 2)) + 'px';
$('.details p').show().not('p:nth-child(' + el + ')').hide();
$('.details')
.css({
top: yPos,
left: xPos
})
.stop()
.fadeIn('fast');
});
$('.title').mouseleave(function() {
var el = $(this).attr('name');
$('.details').fadeOut('fast');
})
.container {
text-align: center;
}
.title {
display: inline-block;
padding: 10px;
background-color: red;
margin-top: 150px;
}
.details {
position: absolute;
top: -300px;
background: #fefefe;
border: 1px solid #aaa;
border-radius: 5px;
padding: 10px;
z-index: 10;
box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.3);
}
.details:after,
.details:before {
top: 100%;
left: 50%;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.details:after {
border-color: rgba(254, 254, 254, 0);
border-top-color: #fefefe;
border-width: 10px;
margin-left: -10px;
}
.details:before {
border-color: rgba(170, 170, 170, 0);
border-top-color: #aaa;
border-width: 11px;
margin-left: -11px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="title" name="1">
Title element 1
</div>
<div class="title" name="2">
Title element 2
</div>
</div>
<div class="details" id="1">
<p>
These are details about the main topic, shown as a blurb on hover.
</p>
<p>
This is a blurb with two lines.
<br> Why isn't the blurb positioned correctly when you first hover over?
</p>
</div>
【问题讨论】: