【问题标题】:How to get position for fixed element without jquery?如何在没有 jquery 的情况下获得固定元素的位置?
【发布时间】:2013-01-11 06:38:28
【问题描述】:

你好

我有一个位置固定的元素,我无法检测位置,必须清楚地使用 javascript,没有框架(jquery、mootools 等)。

【问题讨论】:

标签: javascript position fixed


【解决方案1】:

用途:

var boundingBox = node.getBoundingClientRect();

查看结果,你有一个像这样的对象:

top    : 0,
right  : 0,
bottom : 0,
left   : 0,
width  : 0,
height : 0

【讨论】:

    【解决方案2】:

    这有帮助吗:

    document.getElementById('id').offsetLeft // + window.scrollX
    document.getElementById('id').offsetTop // + window.scrollY
    

    你可能想看看:This Question

    【讨论】:

    • 如果你想得到和jQuery一样的结果,你需要减去margin。
    【解决方案3】:
    function findPos(obj) {
    
        var curleft = curtop = 0;
    
        if (obj.offsetParent)
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
    
        } while (obj = obj.offsetParent);
    
        return [curleft,curtop];
    }
    

    http://www.quirksmode.org/js/findpos.html

    【讨论】:

    • 您首先有语法问题,您打开“{”(查看“if (obj.offsetParent) {”)但您没有关闭它!无论如何,这不适用于滚动的 div。
    【解决方案4】:

    对于跨平台解决方案,您可能需要查看微框架 Popper.js 源代码。我通过尝试解决这个 popper 问题找到了您的问题,但我相信它适用于任何固定元素。

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      相关资源
      最近更新 更多