我正在制作这个简单的工具提示,我想将工具提示底部定位在父元素的顶部。我想通过获取工具提示元素的高度并将这个负数设置为顶部定位来做到这一点。 问题是,根据 console.log();,当我悬停该元素时,工具提示高度为 0;
$('.tooltip').hover(function() {
var content = $(this).data('tip-content');
var element = $(this).find('.tip-content');
if(element.length == 0 ) {
var html = $('<p class="tip-content">' + content + '</p>');
var height = html.height();
console.log(height);
html.css('top', - height);
$(this).prepend(html);
} else {
element.remove();
}
});
.element {
height: 50px;
width: 50px;
margin: 50px auto;
background: #000;
}
.tooltip {
position: relative;
}
.tooltip .tip-content {
width: 180px;
margin-left: -98px;
padding: 10px 5px;
position: absolute;
left: 50%;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background: #294a72;
font-size: 0.75em;
color: #fff;
text-align: center;
}
.tooltip .tip-content:after {
top: 100%;
left: 50%;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
border-top-color: #294a72;
border-width: 5px;
margin-left: -5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element tooltip" data-tip-content="This is a test content">
</div>
最佳答案
在您检查高度时,元素尚未添加到 DOM,因此可能没有高度。您只需要切换语句的顺序。 jQuery 可以并且将会更改元素的 CSS,即使在添加元素之后也是如此。
var html = $('<p class="tip-content">' + content + '</p>');
$(this).prepend(html); //This line must go before the next
var height = html.height();
console.log(height);
但是,您仍然缺少一些部分。 height()
不包括边距或填充。要获得填充,您可以使用 outerHeight()
,但您必须从 CSS 读取边距或使用硬编码值。更糟糕的是,您的箭头使用的是伪元素,*不能* 可通过 DOM 遍历读取,因此遗憾的是,您最好的选择就是对其进行硬编码。
更好的高度计算可能如下所示:
var ARROW_HEIGHT = 5;
html.outerHeight() + parseInt(html.css('marginBottom'), 10) + ARROW_HEIGHT;
关于javascript - 定位顶部父元素的底部元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32209457/