LoginSignup
5
5

More than 5 years have passed since last update.

Firefoxのelement.offsetTopが上手く動かないときはElement.getBoundingClientRect()を使う

Last updated at Posted at 2015-03-17

FirefoxでoffsetTop/offsetLeftが上手く動かない(ことがある)

Firefox(36.0.1)でelement.offsetTopが上手く動かないことがあります。
例えば487個のspanから順番にoffsetTopを取った時、期待した値と違う値が取れることがあるます。

残念ながら再現コードはありません。

代わりにElement.getBoundingClientRect()使う

Element.getBoundingClientRect()を使うと正しい位置が取れます。

ただし、offsetTopと違い絶対位置を取得します。
相対位置を取るにはoffsetParentの位置を引きます。

<style>
    .base,
    .main {
        position: relative;
        top: 25px;
    }

    .base {
        background-color: blue;
        width: 100px;
        height: 100px;
    }

    .main {
        background-color: red;
        width: 50px;
        height: 50px;
    }
</style>
<div class="base">
    <div class="main">
    </div>
</div>
<script>
    var element = document.querySelector('.main')
    console.log(element.offsetTop) //25
    console.log(element.getBoundingClientRect().top) //58
    console.log(element.getBoundingClientRect().top - element.offsetParent.getBoundingClientRect().top) //25
</script>

こんな感じです。

動くサンプルです。
http://jsfiddle.net/4hjbzc20/

Firefoxでも487個のspanからoffsetTopを取れます。

参考になるリンク

jQuery最高!

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5