這是我的 html 代碼:
<body>
<p id="text">Change my style</p>
<div>
<button id="jsstyles" onclick="style()">Style</button>
</div>
</body>
這是我的javascript:
function style()
{
Text.style.fontSize = "14pt";
Text.style.fontFamily = "Comic Sans MS";
Text.style.color = "red";
}
我在這段代碼中沒有看到問題,它仍然無法正常作業
uj5u.com熱心網友回復:
應該text不是Text。
甚至更好地使用document.getElementById.
在 window 物件上使用命名訪問是不受歡迎的。 帶有 id 的 DOM 樹元素會成為全域變數嗎?
uj5u.com熱心網友回復:
正如 Barmer 在評論中提到的,您沒有設定變數。
更重要的是,您不能將其style用作 avariable或functionname。我試圖style用作funtion名稱,但它產生了errorwhere styleis not afunction
這應該有效:
<body>
<p id="text">Change my style</p>
<div>
<button id="jsstyles" onclick="styles()">Style</button>
</div>
</body>
var Text = document.getElementById('text')
function styles()
{
Text.style.fontSize = "14pt";
Text.style.fontFamily = "Comic Sans MS";
Text.style.color = "red";
}
uj5u.com熱心網友回復:
你的代碼有幾個問題
- 您需要將變數設定為要在 javascript 中更改的元素。
- 您無法命名您的函式,
style()因為名稱樣式已在 javascript 中使用。而是嘗試不同的名稱,例如handleStyle()或其他名稱。
// Set variable to what element you want to change
const Text = document.querySelector("#text");
// For this example I use handleStyle for the function
function handleStyle() {
Text.style.fontSize = "14pt";
Text.style.fontFamily = "Comic Sans MS";
Text.style.color = "red";
}
<body>
<p id="text">Change my style</p>
<div>
<button id="jsstyles" onclick="handleStyle()">Style</button>
</div>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/362877.html
標籤:javascript html 功能 造型
上一篇:FullCaledar不顯示事件
下一篇:布爾運算子行為
