使用它设置元素的偏移量时jQuery.offset({coords}),还会将CSS属性设置position为absolute.
然而,我有一个div,我设置position: fixed在我的CSS中,我希望它保持这种方式,即使在使用jQuery设置元素的偏移量之后.
现在,我敢肯定,我大概可以设置偏移,则设定position: fixed了,但我不知道是否有一种方法,我可以告诉jQuery来的位置设置为固定的,而不是绝对的,当它设置偏移.
HTML
<div class="searchResults">
...
</div>
Run Code Online (Sandbox Code Playgroud)
CSS
DIV.searchResults {
position: fixed;
padding: 20px;
background-color: red;
z-index: 501;
}
Run Code Online (Sandbox Code Playgroud)
jQuery的
$("DIV.searchResults").offset({left: 0, top: 0});
Run Code Online (Sandbox Code Playgroud)
呈现HTML
<div class="searchResults" style="position: absolute; top: 0px; left: 0px;">
...
</div>
Run Code Online (Sandbox Code Playgroud)
显然,由于jQuery在样式中设置位置,它将胜过我的CSS类的值.所以,我需要一种方法来告诉jQuery的设置position来fixed代替absolute,或者告诉它设置偏移不设置CSS属性的值position.
axe*_*hel 11
正如我上面评论的那样,在您的情况下,您只需要修改顶部和左侧的CSS,如下所示:
$("DIV.searchResults").css({left: 0, top: 0});
Run Code Online (Sandbox Code Playgroud)
因为$ .offset setter方法只操纵left,top和position值来使元素相对于页面(从静态到相对,从固定到绝对).由于您希望将其定位,请直接设置值.