簡體   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