javascript jQuery.offset() 设置位置:绝对。我需要位置:固定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14730118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:26:12  来源:igfitidea点击:

jQuery.offset() sets position: absolute. I need position: fixed

javascriptjquery

提问by crush

When you set an element's offset with jQuery.offset({coords})it also sets the CSS property positionto absolute.

当您使用jQuery.offset({coords})它设置元素的偏移量时,也会将 CSS 属性设置positionabsolute

I have a div, however, that I set to position: fixedin my CSS, and I want it to remain that way, even after setting the offset of the element with jQuery.

但是,我position: fixed在 CSS 中设置了一个 div,我希望它保持这种状态,即使在使用 jQuery 设置元素的偏移量之后也是如此。

Now, I'm sure I can probably set the offset, then set position: fixedagain, but I was wondering if there is a way I can tell jQuery to set the position to fixed instead of absolute when it sets offset.

现在,我确定我可以设置偏移量,然后position: fixed再次设置,但我想知道是否有办法告诉 jQuery 在设置偏移量时将位置设置为固定而不是绝对。

HTML

HTML

<div class="searchResults">
    ...
</div>

CSS

CSS

DIV.searchResults {
    position: fixed;
    padding: 20px;
    background-color: red;
    z-index: 501;
}

jQuery

jQuery

$("DIV.searchResults").offset({left: 0, top: 0});

Rendered HTML

呈现的 HTML

<div class="searchResults" style="position: absolute; top: 0px; left: 0px;">
    ...
</div>

Obviously, since jQuery is setting the position in the style, it will trump the value of my CSS class. So I need a way to tell jQuery to set positionto fixedinstead of absolute, or tell it to set the offset without setting the value of the CSS property position.

显然,由于 jQuery 在样式中设置位置,它将胜过我的 CSS 类的值。所以我需要一种方法来告诉 jQuery 设置positionfixed而不是absolute,或者告诉它设置偏移量而不设置 CSS 属性的值position

回答by axel.michel

As I commented above, in your case all you need is to modify the CSS for top and left like this:

正如我上面评论的那样,在您的情况下,您只需要像这样修改顶部和左侧的 CSS:

$("DIV.searchResults").css({left: 0, top: 0});

Because the $.offset setter method only manipulates the left, top and position values to make the element relative to the page (from static to relative, and from fixed to absolute). Since you want it position fixed, set the values directly.

因为 $.offset setter 方法只操作 left、top 和 position 值,使元素相对于页面(从静态到相对,从固定到绝对)。由于您希望它的位置固定,请直接设置值。

回答by Céryl Wiltink

Maybe not that elegant, but I think you can just chain .css()after that to be sure that positionis set to fixedlike this:

也许不是那么优雅,但我认为你可以在.css()之后链接以确保position设置为fixed这样:

jquery

查询

$("DIV.searchResults").offset({
    left: 0, 
    top: 0
}).css("position" : "fixed");

Not tested, but I think that'll work.

没有经过测试,但我认为这会奏效。