我遇到了一个JavaScript问题,我写的是为了更改<input type="text">
元素和<p>
元素中的字体。
function tnrchan() {
document.getElementsByClassName("pedfields").style.fontFamily = "Times New Roman";
document.getElementById("preview").style.fontFamily = "Times New Roman";
}
function bschan() {
document.getElementsByClassName("pedfields").style.fontFamily = "Brush Script MT";
document.getElementById("preview").style.fontFamily = "Brush Script MT";
}
&#13;
<fieldset>
<legend>Pick Your Font</legend>
<table>
<tr>
<th id="tms">Times New Roman</th>
<th><input type="radio" id="tmsr" name="font" onclick="tnrchan()" checked="checked"></th>
</tr>
<tr>
<th id="bs">Brush Script</th>
<th><input type="radio" id="bsr" onclick="bschan()" name="font"></th>
<th> More Fonts Coming Soon!</th>
</tr>
<tr>
<th id="al">Arial</th>
<th><input type="radio" id="alr" name="font"></th>
</tr>
<th id="fs">French Script MT</th>
<th><input type="radio" id="fsr" name="font"></th>
</table>
</fieldset>
<fieldset>
<legend>Preview</legend>
<p id="preview">This Is What Your Words Will Look Like!</p>
<br>
<label>Try It Out!<br><input type="text" class="pedfields"placeholder="EXAMPLE..."></label>
</fieldset>
&#13;
我希望<input>
和<p>
的font-family在调用函数时更改为其中一种字体。
任何人都知道我做错了什么?
编辑我明白了。它需要以下代码:
function changeFont(fontName) {
var list = document.getElementsByClassName("preview");
for (i = 0; i < list.length; ++i) {
list[i].style.fontFamily = fontName;
}
}
&#13;
<fieldset>
<legend>Pick Your Font</legend>
<table>
<tr>
<th id="tms">Times New Roman</th>
<th><input type="radio" id="tmsr" name="font" onclick="changeFont('Times New Roman')" checked="checked"></th>
</tr>
<tr>
<th id="bs">Brush Script</th>
<th><input type="radio" id="bsr" onclick="changeFont('Brush Script MT')" name="font"></th>
<th> More Fonts Coming Soon!</th>
</tr>
<tr>
<th id="al">Arial</th>
<th><input type="radio" id="alr" onclick="changeFont('Arial')" name="font"></th>
</tr>
<th id="fs">French Script MT</th>
<th><input type="radio" id="fsr" onclick="changeFont('French Script MT')" name="font"></th>
</table>
</fieldset>
<fieldset>
<legend>Preview</legend>
<p id="preview" class="preview">This Is What Your Words Will Look Like!</p>
<br>
<label>Try It Out!<br><input type="text" class="preview" placeholder="EXAMPLE..."></label>
</fieldset>
&#13;
答案 0 :(得分:3)
document.getElementByClassName("pedfields")
它表示元素, s ,复数。
返回NodeList,而不是Element。你必须像数组一样循环它。
.style.font-family
标识符不能包含-
个字符。它们是减法运算符。您需要切换到camelCase:fontFamily
。
答案 1 :(得分:0)
通常,CSS中的任何带连字符的属性都将成为JavaScript中的camelCased属性。因此,您将使用style.fontFamily
。
但是,我建议切换/应用元素的类,让CSS控制细节。