<!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,用這個公式可以將標題居中在其背景中元素嘗試使用Javascript獲取h1標籤的寬度
我你說的做了什麼,但現在它顯示爲1282 – user1355016 2012-04-25 01:46:13
這意味着,你的元素在其默認寬度(100%)。在獲得offsetWidth之前試一下:document.getElementById(「slidehsowheading」)。style.display =「inline-block」;' 然後,在這之後,您可以將其恢復爲塊樣式: 'document.getElementById ( 「slidehsowheading」)的style.display = 「塊」;' – 2012-04-25 02:53:21