【问题标题】:jQuery Get top offset relative to a specific divjQuery获取相对于特定div的顶部偏移量
【发布时间】:2013-06-20 16:20:52
【问题描述】:

使用 jQuery,您将如何找到相对于特定容器的偏移位置?

例如,你有这个:

<body style="padding:20px"> 
<div id="top-container" style="margin-top:20px"> 
    <div id="one-level-container" style="margin-top:70px"> 
        <div id="two-level-container" style="margin-top:120px"> 
            <div id="ELEMENT" style="margin-top:10px"> 
            </div> 
        </div> 
    </div> 
</div>
</body>

(padding 和 margin-top 仅用于示例。)

如何检查#ELEMENT 的顶部位置到#top-container?

我尝试过使用 jQuery 的偏移量和位置,但它们似乎没有得到我正在寻找的正确偏移量。

【问题讨论】:

    标签: javascript jquery position offset


    【解决方案1】:

    例如使用$.offset()

    alert($("#ELEMENT").offset().top - $("#top-container").offset().top)
    body {
        background: blue
    }
    
    div {
        padding: 20px
    }
    
    #top-container {
        background: green
    }
    
    #one-level-container {
        background: red
    }
    
    #two-level-container {
        background: black
    }
    
    #ELEMENT {
        background: orange
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <body style="padding:20px"> 
    <div id="top-container" style="margin-top:20px"> 
        <div id="one-level-container" style="margin-top:70px"> 
            <div id="two-level-container" style="margin-top:120px"> 
                <div id="ELEMENT" style="margin-top:10px"> 
                </div> 
            </div> 
        </div> 
    </div>
    </body>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多