$(".leftmenu_main li").hover(function () {
$(this).addClass('hover');
var menuTop = $(this).offset().top;
var itemsList = $(this).children(".sec_cd");
var itemsCount = itemsList.find('.sec_icon').length;
itemsList.css("top", subMenuTop).fadeIn("fast");
}, function () {
$(".sec_cd").hide();
$(this).removeClass('hover');
});
phpcn_u15822017-05-19 10:27:01
Give me a chestnut
So offset calculates not the height from the parent, but the top and left margins from the body.
曾经蜡笔没有小新2017-05-19 10:27:01
html
<p class="a">
<p class="b"></p>
</p>
css
.a{
position: relative;
width: 200px;
height: 200px;
background-color: #f33;
top: 200px;
}
.b{
position: absolute;
width: 100px;
height: 100px;
background-color: #1abc9c;
top: 120px;
}
js
console.log($('.b').offset().top);
offset().top is the final result of 层层向上
relative to the body
Note that it is upward layer by layer. No matter how many parents are positioned in the middle, or how many top offsets there are in the middle, they will be superimposed. .
It can also be achieved with native JS:
export function getTop(obj) {
var iTop = 0;
while (obj != window.document.body && obj != null) {
iTop += obj.offsetTop; //循环取每一层父元素的相对偏移量
obj = obj.offsetParent; //设置当前元素的父元素=当前元素,用以获取再上层的offsetTop
}
return iTop;
}
phpcn_u15822017-05-19 10:27:01
It depends on whether you have written the positioning parent. If there is no positioning parent, it is the body
黄舟2017-05-19 10:27:01
为什么不查 API。
Get the current coordinates of the first element in the set of matched elements, relative to the document.