Home >Web Front-end >Front-end Q&A >javascript change font
Javascript can easily change fonts in web pages. Font changes can be achieved by modifying the font properties in the style sheet or directly modifying the style of the text element.
Here are two basic ways to change fonts using Javascript:
In Javascript , we can use the document.styleSheets
property to access the style sheet, and the cssRules
property to access the style rules. We can find the rule that needs to modify the font properties, and then modify its font properties to a new font.
The following is a sample code:
// 找到需要修改字体的样式规则 var styleSheets = document.styleSheets; for (var i = 0; i < styleSheets.length; i++) { var rules = styleSheets[i].cssRules || styleSheets[i].rules; for (var j = 0; j < rules.length; j++) { if (rules[j].selectorText === 'body') { // 修改字体属性 rules[j].style.fontFamily = 'Arial, sans-serif'; } } }
This code changes the font attribute of the body element to Arial, sans-serif
.
We can also directly modify the style of text elements. We can find the element whose font needs to be modified, and then modify the font attribute in its style to the new font.
The following is a sample code:
// 找到需要修改字体的元素 var elements = document.getElementsByTagName('p'); for (var i = 0; i < elements.length; i++) { // 修改字体属性 elements[i].style.fontFamily = 'Arial, sans-serif'; }
This code changes the font attributes of all e388a4556c0f65e1904146cc1a846bee
elements in the page to Arial, sans-serif
.
The above are the two basic methods of changing fonts using Javascript. By modifying the style sheet or directly modifying the element style, we can easily achieve the effect of changing fonts.
The above is the detailed content of javascript change font. For more information, please follow other related articles on the PHP Chinese website!