我試圖讓這個吃豆子影片在一系列影像中回圈并在它到達頁面邊緣時反轉方向。
我嘗試在 Chrome 中除錯,它給了我以下錯誤
“無法讀取 null 的屬性(讀取寬度)”
var pos = 0;
//pageWidth is the width of the webpage. This is later used to calculate when Pac-Man needs to turn around.
const pageWidth = window.innerWidth;
//This array contains all the PacMan movement images
const pacArray = [
['./images/PacMan1.png', './images/PacMan2.png'],
['./images/PacMan3.png', './images/PacMan4.png'],
];
// this variable defines what direction should PacMan go into:
// 0 = left to right
// 1 = right to left (reverse)
var direction = 0;
// This variable helps determine which PacMan image should be displayed. It flips between values 0 and 1
var focus = 0;
// This function is called on mouse click. Every time it is called, it updates the PacMan image, position and direction on the screen.
function Run() {
let img = document.getElementById('PacMan');
let imgWidth = img.width;
let pageWidth = window.innerWidth;
focus = (focus 1) % 2;
direction = checkPageBounds(direction, imgWidth, pos, pageWidth);
img.src = pacArray[direction][focus];
if (direction) {
pos -= 20;
img.style.left = pos 'px';
} else {
pos = 20;
img.style.left = pos 'px';
}
}
setInterval(Run,200)
// This function determines the direction of PacMan based on screen edge detection.
function checkPageBounds(direction, imgWidth, pos, pageWidth) {
if (direction == 1 & pos imgWidth > pageWidth) direction== 0;
if (direction == 0 & pos < 0) direction == 1;
//
return direction;
}
module.exports = checkPageBounds;
uj5u.com熱心網友回復:
該錯誤表示您正在嘗試width從null.
查看您的代碼,它可能與這一行有關:
let imgWidth = img.width
注意:錯誤實際上會告訴您發生錯誤的確切行號和字符索引。
這意味著,在Run呼叫您的函式時,document.getElementById('PacMan')回傳null.
它可能意味著以下之一:
- 你拼錯了
PacMan - 您已將
<script>標記放在#PacMan元素上方,因此具有該 id 的元素尚未添加到 DOM。
如果我們處理后者,請注意,默認情況下,<script>一旦 DOM 決議器遇到標簽,就會執行內容。以下是延遲其執行直到所有 DOM 內容加載完畢的方法:
<script>
window.addEventListener('DOMContentLoaded', () => {
console.log('DOM fully loaded and parsed');
// place your script in here. It will find `#PacMan` even if
// the element with that id is placed later in DOM than this script
});
</script>
uj5u.com熱心網友回復:
您的示例未顯示模板/html。元素 id (PacMan) 是否正確寫入?
此示例應在控制臺中列印 200:
<img id="PacMan" src="https://picsum.photos/200/300" />
const img = document.getElementById('PacMan');
let imgWidth = img.width;
只是一點題外話的建議:看看“var”、“const”和“let”之間的區別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/383008.html
標籤:javascript 动画片 吃豆子
