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.
<p>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'; } } }
Arial, sans-serif
. // 找到需要修改字体的元素 var elements = document.getElementsByTagName('p'); for (var i = 0; i < elements.length; i++) { // 修改字体属性 elements[i].style.fontFamily = 'Arial, sans-serif'; }
<p>
elements in the page to Arial, sans-serif
.
<p>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!