我有這個示例顯示來自用戶的一些任意文本:
<html>
<head></head>
<body>
<%= @article.text %>
</body>
</html>
我想知道如何使用 Ruby 獲取 HTML 元素(例如 @article.text)的 X 和 Y 位置。
uj5u.com熱心網友回復:
為元素設定一些 id
<html>
<head></head>
<body>
<div id="my-id">
<%= @article.text %>
</div>
</body>
</html>
并在 JS 中獲得位置getBoundingClientRect
const getCoordinates = (element) => {
const box = element.getBoundingClientRect()
return {
top: box.top window.pageYOffset,
right: box.right window.pageXOffset,
bottom: box.bottom window.pageYOffset,
left: box.left window.pageXOffset
}
}
const element = document.getElementById('my-id')
const coordinates = getCoordinates(element)
console.log(coordinates)
參考:
https://javascript.info/坐標
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/481769.html
