简体   繁体   English

在SVG元素上获取offsetTop

[英]get offsetTop on SVG element

Why is offsetTop returning undefined on this SVG element? 为什么offsetTop在此SVG元素上返回undefined

 var svg = document.querySelector('svg') var h1 = document.querySelector('h1') console.log('svg', svg.offsetTop) console.log('h1', h1.offsetTop) 
 <svg width="26" height="30" viewBox="0 0 12 14"> <path d="M6 4.038L12 0v3.623L6 8 0 3.623V0l6 4.038zm0 6L12 6v3.623L6 14 0 9.623V6l6 4.038z"/> </svg> <h1>This works</h1> 

The inheritance tree for DOM elements has Element as a base class with SVGElement and HTMLElement deriving separately from that. DOM元素的继承树将Element作为基类,其中SVGElement和HTMLElement分别派生于此。 offsetTop is defined on the HTMLElement interface and not on the Element interface so SVG elements don't support it. offsetTop是在HTMLElement接口定义的,而不是在Element接口上定义的,因此SVG元素不支持它。

You could get this information by calling element.getBoundingClientRect() instead. 您可以通过调用element.getBoundingClientRect()来获取此信息。 This would work for all elements. 这将适用于所有元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM