LoginSignup
1
1

More than 5 years have passed since last update.

SVGでoffsetの取得ができない(safari)

Last updated at Posted at 2018-05-14

はじめに

SVGのアニメーションを実装している時にひっかかったので、備忘録です。

事象

下記のようにoffset().Topを取得して、位置判定に使用するつもりでした。
chrome,firefox,androidではきちんと取得できていたのに、safariだけ取得できず、値が0になっていました。

index.html
<svg class="line" width="100%" height="73" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
          <line class="animationLine" x1="0" y1="2" x2="100%" y2="2" stroke="#a2bdd4" stroke-width="2"></line>
</svg>
index.js
const $animationLine = $('.animationLine');
this.animationLineTop = $animationLine.offset().Top;

解決策

jqueryを使うかどうかで要素の指定の仕方が少し変わりますが、'.offset().Top'のかわりに、'.getBoundingClientRect().top'を使うのはどちらでも一緒です。

index.js
const $animationLine = $('.animationLine');
this.animationLineTop = $animationLine[0].getBoundingClientRect().top;
index.js
const $animationLine = document.getElementsByClassName('animationLine');
this.animationLineTop = $animationLine.getBoundingClientRect().top;

おわりに

この事象に出会うまで、SVGでoffsetの取得ができないと知りませんでした。
これ以外の解決法を知りたいのでご存知の方いらっしゃいましたら、教えてください。

1
1
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
1
1