所以我有一個簡單的 html 檔案,它由一個 div 組成;和一個 css 檔案,它具有上述 div 的簡單樣式:
html :
<html>
<head>
<title>Simple Movement</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="index.js"></script>
</head>
<body>
<div id="square"></div>
</body>
</html>
css:
body {
margin: 0;
}
#square {
width: 100px;
height: 100px;
border: 1px solid #095057;
background-color: #20979e;
position: absolute;
left: 200px;
top: 200px;
}
在我的 js 檔案中,我做了一個簡單的日志,如下所示:
console.log(document.getElementById('square').style.top)
但我收到一個錯誤:
Uncaught TypeError: Cannot read properties of null (reading 'style') at index.js:1
我不知道為什么它說樣式為空。你呢?
uj5u.com熱心網友回復:
我不知道為什么它說樣式為空。你呢?
它沒有。它說,document.getElementById('square')回傳null所以您選擇讀取屬性style上null的錯誤,結果。
發生這種情況是因為您的腳本是在頭部加載(并執行)的。此時,DOM 中還不存在 ID 為“square”的元素。
將您的腳本移到您的元素下方(請參閱代碼段)或使用async defer如下標記:<script src="index.js" async defer></script>使其在DOM 決議完成后加載并執行。
此外,訪問style將僅顯示來自 style 屬性的行內樣式,因此不會從樣式表檔案(或行內樣式表)中獲取值。
使用computedStyleMap()(參見https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap)獲取包括所有樣式表在內的實際計算樣式。
body {
margin: 0;
}
#square {
width: 100px;
height: 100px;
border: 1px solid #095057;
background-color: #20979e;
position: absolute;
left: 200px;
top: 200px;
}
<html>
<head>
<title>Simple Movement</title>
<meta charset="UTF-8">
</head>
<body>
<div id="square"></div>
<script>
console.log(document.getElementById('square').computedStyleMap().get('top').value);
</script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347490.html
標籤:javascript html css
上一篇:使用Javascript腳本中DIV中的動態ImgSrcURL
下一篇:從員工網頁上抓取期刊文章標題
