繁体   English   中英

如何使用JavaScript更改输入元素和文本的字体系列?

[英]How do you change the font-family of a input element and text with JavaScript?

我有一个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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;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>的font-family在调用函数时更改为其中一种字体。

任何人都知道我做错了什么?

编辑我得到了它的工作。 它需要以下代码:

 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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;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

标识符不能包含-字符。 它们是减法运算符。 你需要切换到camelCase: fontFamily

通常,CSS中的任何带连字符的属性都将成为JavaScript中的camelCased属性。 因此,您将使用style.fontFamily

但是,我建议切换/应用元素的类,让CSS控制细节。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM