我想在 JavaScript 中更改字体类型和大小
2020-09-05
328
我不断获得错误
< a class ='gotoline'href ='#36:31'> 36:31</a>未定义的TypeError:无法将属性设置为未定义的
881176714
3个回答
更新您的 JS 函数为,
function myFunction() {
document.getElementById("demo").innerHTML = document.getElementsByTagName('input')[0].style.fontFamily = "Impact,Charcoal,sans-serif";
}
Nikhil Singh
2020-09-05
var x = document.getElementById("myText").value; var x2 = x.style.fontFamily = "Impact,Charcoal,sans-serif";
在上面的代码中,您将值分配给
x
,然后尝试更改
font family
。但 x 的类型为
string
,字符串没有任何名为
style
的属性,因此
x.style
将为
undefined
。这就是在尝试访问
undefined
值上的
fontFamily
时出现错误
Cannot set property 'fontFamily' of undefined
的原因。
因此,不要将
document.getElementById("myText").value
分配给
x
,而是将
document.getElementById("myText")
分配给
x
。
<!DOCTYPE html>
<html>
<body>
First Name: <input type="text" id="myText" value="Mickey">
<p>Click the button to display the value of the value attribute of the text field.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myText");
x.style.fontFamily = "Impact,Charcoal,sans-serif";
var x2 = document.getElementById("demo");
x2.style.fontFamily = "Impact,Charcoal,sans-serif";
x2.innerHTML = x.value;
}
</script>
</body>
</html>
Nithish
2020-09-05
您的 javascript 中存在一些错误。我已修复。
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("myText");
document.getElementById("demo").innerHTML=x.value;
var y = document.getElementById("demo");
y.style.fontFamily="Impact Charcoal sans-serif";
y.style.border = "3px solid red";
}</script>
</head>
<body>
First Name: <input type="text" id="myText" value="Mickey">
<p>Click the button to display the value of the value attribute of the text field.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
Sandrin Joy
2020-09-05