我在编写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";
}
<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>
我希望在调用函数时将<input>
和的字体系列<p>
更改为其中一种字体。
有人知道我在做什么错吗?
编辑我得到它的工作。它需要以下代码:
function changeFont(fontName) {
var list = document.getElementsByClassName("preview");
for (i = 0; i < list.length; ++i) {
list[i].style.fontFamily = fontName;
}
}
<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>
document.getElementByClassName("pedfields")
它使用s表示复数元素。
这将返回一个NodeList,而不是一个Element。您必须像数组一样遍历它。
.style.font-family
标识符不能包含-
字符。他们是减法运算符。你需要切换到驼峰:fontFamily
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句