提问人:Forest Fire 7 提问时间:9/21/2023 更新时间:9/22/2023 访问量:34
无法通过 JavaScript 获取用于将元素定位到中心的元素高度
Can't get the element height for positioning an element to center by JavaScript
问:
我正在尝试使用 JavaScript 将跨度居中放在段落内。这是我的代码:
document.addEventListener('DOMContentLoaded', () => {
window.onload = function(){middle();}
var titleHeight = document.getElementById("page-title").clientHeight;
var titleWidth = document.getElementById("page-title").clientWidth;
var objHeight = document.getElementById("head-text").clientHeight;
var objWidth = document.getElementById("head-text").clientHeight;
var moveit = document.getElementById("head-text");
var moveit = document.getElementById("head-text");
function middle(){
console.log(titleHeight/2-objHeight/2);
moveit.style.top=titleHeight/2-objHeight/2;
moveit.style.left=titleWidth/2-objWidth/2);
}
})
它始终为 titleHeight 返回 undefined。我该如何解决这个问题?
我尝试通过css使元素居中,但这无济于事。所以我不得不改用 JavaScript。我需要任何可能的JavaScript来定位我的元素。
答:
0赞
Keith
9/21/2023
#1
你真的应该用CSS来做到这一点,但是在JS中,你需要调用才能获得准确的位置信息。element.getBoundingClientRect()
此外,您还设置为 .objWidth
clientHeight
它很慢,会导致卡顿,但是......
document.addEventListener('DOMContentLoaded', () => {
window.onload = function(){middle();}
function middle(){
// This can change, so needs to be in the `middle` function
const title = document.getElementById("page-title").getBoundingClientRect();
const titleHeight = title.height;
const titleWidth = title.width;
const moveit = document.getElementById("head-text");
const head = moveit.getBoundingClientRect();
const objHeight = title.height;
const objWidth = title.width; // fix typo
console.log(titleHeight/2-objHeight/2);
moveit.style.top=(titleHeight/2-objHeight/2)+"px";
moveit.style.left=(titleWidth/2-objWidth/2)+"px";
}
})
0赞
Klas
9/22/2023
#2
可能会有问题,因为 span 是默认的内联 html。尝试在 javascript 操作之前设置 css 并将其定义为 inline-block:
span: { display: inline-block}
评论
load
DOMContentLoaded