代码之家  ›  专栏  ›  技术社区  ›  Red

在普通javascript中获得正确的偏移量

  •  1
  • Red  · 技术社区  · 6 年前

    如何获取元素相对于 window 是吗?

    我只能找到jquery解决方案,但我需要一个使用普通javascript的解决方案。

    这是使用jquery的解决方案

    var rt = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));
    

    如何将其转换为普通javascript?

    5 回复  |  直到 6 年前
        1
  •  5
  •   MysterX    6 年前

    你不能试着用 element.getBoundingClientRect() 为了达到这种行为。因此,如果在没有jquery的情况下翻译您的代码,它将如下所示:

    var rt = window.innerWidth - element.getBoundingClientRect().right;
    
        2
  •  1
  •   Luis felipe De jesus Munoz    6 年前
    • 可以使用 .innerWidth
    • 可以使用 getBoundingClientRect()
    • 你可以用 offsetWidth

    移植您的解决方案应该是这样的:

    window.innerWidth - (element.getBoundingClientRect().left + element.offsetWidth)
    

    有关更多信息,您可以查看 this link

        3
  •  0
  •   Simeon Smith    6 年前

    可以使用元素的.OffsetLeft属性获取左偏移位置。 https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetLeft

    有关外部宽度,请参见以下答案: outerWidth without jquery

    所以它会被写成:

    var rt = function() {
      var someElement = document.getElementById('someID');
      return window.innerWidth - (someElement.offsetLeft + someElement.offsetWidth);
    }
    
        4
  •  0
  •   Moritz Roessler    6 年前

    只需获取窗口大小,然后减去x偏移量加上要获取偏移量的元素的宽度。

    function windowOffsetRight (ele) { 
        let rect = ele.getBoundingClientRect (); 
        let width = document.documentElement.getBoundingClientRect().width;
        return  width - ( rect.x + rect.width)
    }
    
        5
  •  0
  •   marc_s    6 年前

    您只需要将jquery函数转换为vanilla js。

    $window() // jQuery
    window // Vanilla JS
    
    $whatever // jQuery (probably a variable of $('.whatever'))
    document.querySelectorAll('.whatever') // Vanilla JS
    
    offset().left // jQuery
    offsetLeft // Vanilla JS
    
    outerWidth() // jQuery
    offsetWidth // Vanilla JS
    

    const el =  document.getElementById('test');
    console.log(window.innerWidth - (el.offsetLeft + el.offsetWidth));
    <div id="test"></div>

    当然还有很多其他的方法。