javascript - Is the displacement height of .offset().top relative to body or .leftmenu_main li? ? ?
ringa_lee
ringa_lee 2017-05-19 10:25:01
0
4
578
$(".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');
});

ringa_lee
ringa_lee

ringa_lee

reply all(4)
phpcn_u1582

Give me a chestnut

So offset calculates not the height from the parent, but the top and left margins from the body.

曾经蜡笔没有小新

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_u1582

It depends on whether you have written the positioning parent. If there is no positioning parent, it is the body

黄舟

为什么不查 API。

Get the current coordinates of the first element in the set of matched elements, relative to the document.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template