javascript - Ist die Verschiebungshöhe von .offset().top relativ zu body oder .leftmenu_main li? ? ?
ringa_lee
ringa_lee 2017-05-19 10:25:01
0
4
582
$(".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

Antworte allen(4)
phpcn_u1582

举个栗子

因此offset计算的不是离距离父级的高度,而是离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是层层向上相对于body的最终结果
注意是层层向上,不管中间有几个父级是position定位的,中间多了多少个top偏移量,都会被叠加进去。

用原生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

那得看你写没写定位父级了,如果没有定位父级那就是body

黄舟

为什么不查 API。

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

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage