尝试使用 Javascript 获取 h1 标签的宽度

Trying to get the width of an h1 tag with Javascript

本文关键字:标签 h1 获取 Javascript      更新时间:2023-09-26
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org    /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type = "text/javascript">
var textHeadingArray = ["Bloom Defender", "Civilization Wars", "Flight", "Rebuild 2",  "Wonderputt"];
var textHeadingIndex = 0;
function changeMainImage() {
textHeadingIndex++;
        if (textHeadingIndex >= textHeadingArray.length) {
        textHeadingIndex = 0;   
}
var changeTheHeading = document.getElementById("slidehsowheading").innerHTML = textHeadingArray[textHeadingIndex];
var heading = document.getElementById("slidehsowheading").style.width;
var sizeOfHeading = heading;
alert(sizeOfHeading);
var subtraction = 75 - sizeOfHeading;
var changeTheHeadingAgain = document.getElementById("slidehsowheading").style.left = subtractionRounded + "px";
}
var mainTiming = setInterval("changeMainImage()", 5000);
</script>
</head>
<body>
<h1 id = "slidehsowheading">Bloom Defender</h1>
</body>
</html>

我试图使用此代码来更改幻灯片的标题,我对 javascript 有点陌生,所以我的问题是当警报弹出时它返回为 null(警报仅用于调试),所以当我尝试使用这个等式中 h1 的空宽度时它是错误的。该等式应该在计时器更改标题并除以 2 后获得标题的宽度,然后从其背景宽度除以 2 中减去该宽度,即 75,使用此公式,您可以将标题在其背景元素中居中

问题是[object].style.width只有在 CSS 中或通过 style.width 方法显式设置宽度时才有效。

请尝试改用 offsetWidth 属性:

var heading = document.getElementById("slidehsowheading").offsetWidth;
你需要在

DOM 加载后执行此操作。把你的javascript放在你身体的末端,而不是在头上。此外,应使用控制台.log而不是警报进行调试。