如何获得元素的“固定”位置?

时间:2012-09-06 04:51:17

标签: javascript jquery

我想获得一个元素相对于窗口的位置(固定位置)。

这是我到目前为止所得到的:

(function ($) {
    $.fn.fixedPosition = function () {
        var offset = this.offset();
        var $doc = $(document);
        return {
            'x': offset.left - $doc.scrollLeft(),
            'y': offset.top - $doc.scrollTop()
        };
    };
})(jQuery);

$('#thumbnails img').click(function () {
    var pos = $(this).fixedPosition();
    console.log(pos);
});

但是当我点击一个缩略图时,它似乎关闭了大约10个像素左右。即使照片的上边缘距浏览器窗口顶部约5个像素,它也会为y提供负值。

3 个答案:

答案 0 :(得分:5)

<强>更新

解决方案现在取决于JSizes和几个辅助方法:

function Point(x, y) {
    return {
        'x': x,
        'y': y,
        'left': x,
        'top': y
    };
}

$.fn.outerOffset = function () {
    /// <summary>Returns an element's offset relative to its outer size; i.e., the sum of its left and top margin, padding, and border.</summary>
    /// <returns type="Object">Outer offset</returns>
    var margin = this.margin();
    var padding = this.padding();
    var border = this.border();
    return Point(
        margin.left + padding.left + border.left,
        margin.top + padding.top + border.top
    );
};


$.fn.fixedPosition = function () {
    /// <summary>Returns the "fixed" position of the element; i.e., the position relative to the browser window.</summary>
    /// <returns type="Object">Object with 'x' and 'y' properties.</returns>
    var offset = this.offset();
    var $doc = $(document);
    var bodyOffset = $(document.body).outerOffset();
    return Point(offset.left - $doc.scrollLeft() + bodyOffset.left, offset.top - $doc.scrollTop() + bodyOffset.top);
};

答案 1 :(得分:1)

您的代码看起来很好,它应该像您期望的那样工作。

也就是说,.offset()有一个“陷阱”,它不会考虑应用于DOM主体的任何填充,边距或边框。它找到元素相对于文档的偏移量,而不是窗口。

http://api.jquery.com/offset/

来自文档:

  

注意:jQuery不支持获取隐藏元素的偏移坐标或者考虑在body元素上设置边框,边距或填充。

有些css应该有望解决这些奇怪的结果:

body { margin: 0; padding: 0; border: none; }

答案 2 :(得分:1)

使用:

element.getBoundingClientRect();

在JQuery插件中:

$.fn.fixedPosition = function () {
    var rect = this.getBoundingClientRect();
    return {
        x: rect.left,
        y: rect.top
    };
};

见:

相关问题