search

Home  >  Q&A  >  body text

javascript - Is the displacement height of .offset().top relative to body or .leftmenu_main li? ? ?

$(".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_leeringa_lee2840 days ago586

reply all(4)I'll reply

  • phpcn_u1582

    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.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新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;
    }
    

    reply
    0
  • phpcn_u1582

    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

    reply
    0
  • 黄舟

    黄舟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.

    reply
    0
  • Cancelreply