我正在使用以下代碼快速分配window.getComputedStyle給變數:
const {
width,
height,
left
} = window.getComputedStyle(document.querySelector('canvas'));
console.log(width, left, height)
<canvas></canvas>
但是當我想宣告時top,它回傳:
未捕獲的 SyntaxError:識別符號頂部已被宣告
const {
width,
height,
left,
top
} = window.getComputedStyle(document.querySelector('canvas'));
console.log(width, left, height)
<canvas></canvas>
但是我之前沒有宣告過它,而且它似乎可以與 left 一起使用。
我錯過了什么?
謝謝。
uj5u.com熱心網友回復:
top是瀏覽器中的全域變數。這意味著它已經在您嘗試定義它的背景關系中定義。您可以將其命名為其他名稱:
const {
width,
height,
left,
top: topStyle, // this basically renames "top" to "topStyle"
} = window.getComputedStyle(document.querySelector('canvas'));
console.log(width, left, height, topStyle)
或者將計算的樣式分配給一個變數并在那里訪問它:
const canvasStyles = window.getComputedStyle(document.querySelector('canvas'));
console.log(
canvasStyles.width,
canvasStyles.left,
canvasStyles.height,
canvasStyles.top
);
或者只是不要嘗試在全域范圍內定義變數。而是在一個函式中定義它:
function accessPosition() {
const {
width,
height,
left,
top
} = window.getComputedStyle(document.querySelector('canvas'));
console.log(width, left, height, top);
}
accessPosition();
uj5u.com熱心網友回復:
如果您打開瀏覽器的開發者工具并輸入:
console.log(top)
您將看到它已被宣告為代表最頂層的視窗。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/488511.html
標籤:javascript html css
上一篇:在JavaScript中創建HTML元素時如何模塊化代碼?
下一篇:無法將所有內容附加到我的投資組合
