gpt4 book ai didi

javascript - 获取 SVG 元素上的 offsetTop

转载 作者:行者123 更新时间:2023-12-03 19:51:55 30 4
gpt4 key购买 nike

为什么是 offsetTop返回 undefined在这个 SVG 元素上?

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>

最佳答案

DOM 元素的继承树以 Element 作为基类,而 SVGElement 和 HTMLElement 分别从该类派生而来。 offsetTop is defined on the HTMLElement interface而不是在 Element 接口(interface)上,所以 SVG 元素不支持它。

您可以调用 element.getBoundingClientRect() 获取此信息反而。这适用于所有元素。

关于javascript - 获取 SVG 元素上的 offsetTop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45969555/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com