【问题标题】:Retrieved $().position() changes after updating to position: absolute更新到位置后检索的 $().position() 更改:绝对
【发布时间】:2012-06-22 10:54:40
【问题描述】:

我正在为 HTML 元素的动态淡入淡出寻找可能的解决方案。我的问题的核心是 jQuery 的 .position() 的一种奇怪行为,并在检索旧位置后更新了 css“位置”属性。

我制作了一个 JSFiddle 来说明我的问题:http://jsfiddle.net/svenhanssen/DDYVs/

/*
This works. I'll get a position.top from 0 to 90
*/

$("p").each(function( p ) {
    var position = $(this).position();

    console.log(position.top);
});

/*
This doesn't work. I'll get a position.top of 0 for all elements. Why does the css set effects the position?
*/

$("p").each(function( p ) {
    var position = $(this).position();

    console.log(position.top);

    $(this).css({
        position: "absolute"
    });
});​

后来以某种方式更改 css“位置”属性会影响旧属性。有谁知道原因和可能的解决方案吗?

【问题讨论】:

    标签: javascript jquery css position absolute


    【解决方案1】:

    当您将<p> 设置为position: absolute 时,它将从文档流中取出,并且下一个非绝对<p> 向上移动以占用释放的空间。然后你会看到刚刚重新定位的<p> 元素,果然它的top 现在是0(因为在它之前没有流入元素可以将其向下推)。

    这是一个可能的解决方案:

    $("p").each(function( p ) {
        var position = $(this).position();
    
        console.log(position.top);
    }).css({
        position: "absolute"
    });​
    

    请注意,现在所有<p> 元素都设置为position: absolute循环滚动之后。

    Updated fiddle

    【讨论】:

    • 这是一个类似的答案,我提供了一个很好的问题可视化:stackoverflow.com/questions/7098283/…
    • @lanzz 你完全正确。我在盯着死亡,但解决方案其实很简单。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 2018-03-10
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    相关资源
    最近更新 更多