Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

はじめに

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の取得ができないと知りませんでした。
これ以外の解決法を知りたいのでご存知の方いらっしゃいましたら、教えてください。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away