我正在尝试允许用户从下拉列表中选择一种字体,该字体将更改应用于他们在表单文本字段中输入的文本的fontFamily。我已经尝试了以下几种变体,但在Safari或Chrome上没有成功。如果有人可以指出我做错了什么,我会很感激。改变颜色有效。更改fontFamily不会。
<html>
<head>
<script>
function setPreview()
{
var myColor = document.getElementById("selectedColor").value;
document.getElementById("inputText").style.color = myColor;
var myFont = document.getElementById("selectedFont").value;
document.getElementByID("inputText").style.fontFamily = myFont;
}
</script>
</head>
<body>
<form>
<label for="uname">Enter Text: </label>
<input type="text" id="inputText" name="name" placeholder="YourName" maxlength="8">
<select name="textColor" id="selectedColor" onchange="setPreview();">
<option value="black" selected="selected">Black</option>
<option value="red">Red</option>
</select>
<select name="textFont" id="selectedFont" onchange="setPreview();">
<option value="Arial" selected="selected">Arial</option>
<option value="Impact">Impact</option>
<option value="Times New Roman">Times New Roman</option>
</select>
</form>
</body>
</html>
答案 0 :(得分:3)
你有一个错字
document.getElementByID("inputText").style.fontFamily = myFont;
ID
应为Id
<强>更新强>
function setPreview() {
var myColor = document.getElementById("selectedColor").value;
document.getElementById("inputText").style.color = myColor;
var myFont = document.getElementById("selectedFont").value;
document.getElementById("inputText").style.fontFamily = myFont;
}
&#13;
<label for="uname">Enter Text: </label>
<input type="text" id="inputText" name="name" placeholder="YourName" maxlength="8">
<select name="textColor" id="selectedColor" onchange="setPreview();">
<option value="black" selected="selected">Black</option>
<option value="red">Red</option>
</select>
<select name="textFont" id="selectedFont" onchange="setPreview();">
<option value="Arial" selected="selected">Arial</option>
<option value="Impact">Impact</option>
<option value="Times New Roman">Times New Roman</option>
</select>
&#13;
答案 1 :(得分:2)
立即运行代码会在控制台中产生错误:
document.getElementByID is not a function
所以,你应该知道这有问题。将.getElementByID
修复为:.getElementById
。
现在,为了获得最佳性能:
将脚本放在文档末尾附近(在解析DOM之后) 缓存您对经常使用的元素的引用 不要为您只使用一次的值设置一个变量
<html>
<head>
</head>
<body>
<form>
<label for="uname">Enter Text: </label>
<input type="text" id="inputText" name="name" placeholder="YourName" maxlength="8">
<select name="textColor" id="selectedColor" onchange="setPreview();">
<option value="black" selected="selected">Black</option>
<option value="red">Red</option>
</select>
<select name="textFont" id="selectedFont" onchange="setPreview();">
<option value="Arial" selected="selected">Arial</option>
<option value="Impact">Impact</option>
<option value="Times New Roman">Times New Roman</option>
</select>
</form>
<script>
var input = document.getElementById("inputText");
var lstColor = document.getElementById("selectedColor");
var lstFont = document.getElementById("selectedFont");
function setPreview() {
input.style.color = lstColor.value;
input.style.fontFamily = lstFont.value;
}
</script>
</body>
</html>
&#13;