getBoundingClientRect() 替代方案

问题描述 投票:0回答:3

我正在使用 document.body.getBoundingClientRect().right 来查找顶部导航中的所有元素都在视图之外,以便隐藏它们并将它们放在“更多”下拉列表下。但这个功能在 safari 中似乎不起作用。该功能是否有其他替代方案,或者有什么方法可以在 safari 中修复它?

var windowRightOffset = document.body.getBoundingClientRect().right,
        elementHiddenFlag = false;

    $(".headerNav").find("li").each(function() {
        if ($(this).className !== 'more') {
            var elemRightOffset = $(this).find("a")[0].getBoundingClientRect().right;
            if (elemRightOffset > windowRightOffset) {
                $(this).hide();
                elementHiddenFlag = true;
                $(".more .moreNavItems-content").append($(this).html());
            }
        }
    });
jquery getboundingclientrect
3个回答
2
投票

由于您使用的是 jQuery,因此您可以查看 jQuery 中的 positionoffset 函数。

用 jQuery 替换你的代码,你会这样做:

var aTag = $(this).find("a")[0];
var left = aTag.offset().left;
var width = aTag.find("a")[0].width();

var aTagRightOffset = width + left;

1
投票

好的,我们走吧:-)

function getBounding(name,index){
    this.ele = document.querySelectorAll(name)[index];
    this.y= this.ele.offsetTop;
    this.x= this.ele.offsetLeft;
    this.coordinates();
  }

  getBounding.prototype.coordinates = function(){
    if( this.ele.localName != "body"){
      this.ele = this.ele.offsetParent;
      this.y += this.ele.offsetTop;
      this.x += this.ele.offsetLeft;
      this.coordinates();
    } else {
      return({x:this.x,y:this.y});
    }
  }

new getBounding(".-img",0)


0
投票

getBoundingClientRect 是offset.top 和窗口scrollTop 的区别


console.log(document.getElementById('elem-id').getBoundingClientRect().top)

console.log($('#elem-id').offset().top-$(window).scrollTop()) 

显示相同的数字。

© www.soinside.com 2019 - 2024. All rights reserved.