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