简体   繁体   English

* {font-family:'Lato'}与js

[英]* { font-family: 'Lato' } with js

I want to set the global font with JS. 我想用JS设置全局字体。

currently css: 目前的CSS:

* {
    font-family: 'Lato'
}

It only works when I use *. 仅在使用*时有效。 using body instead does not work 相反,使用身体不起作用

I could change if for body like this: 我可以为这样的身体而改变:

document.body.style.fontFamily = "Lato"

But I want a js version for the * selector. 但是我想要*选择器的js版本。

You'll need to append a style element to do this reasonably. 您需要附加一个style元素才能合理地做到这一点。 (To do it un reasonably, spin through every element on the page and set it via .style . See below.) (要做到这一点合理,自旋通过页面上的每一个元素,并通过设置.style见下图。)

It's easy enough to do: 这很容易做到:

var style = document.createElement("style");
style.type = "text/css";
style.appendChild(
    document.createTextNode("* { font-family: 'Lato' }")
);
document.head.appendChild(style);

Of course, all the normal CSS rules apply. 当然,所有正常的CSS规则都适用。 An element with a more-specific rule setting font-family , or a .style property setting it, will still use that more-specific setting. 具有更特定规则设置font-family.style属性设置的.style ,仍将使用该更特定设置。

This has the advantage that it applies to new elements added after you've done it as well as existing elements. 这样做的好处是,它适用于完成后添加的新元素以及现有元素。


If you wanted to visit every element on the page to set .style.fontFamily explicitly on each, the quick-and-dirty version on modern browsers is: 如果要访问页面上的每个元素以在每个元素上显式设置.style.fontFamily ,则现代浏览器上的快捷版本是:

Array.prototype.forEach.call(document.getElementsByTagName("*"), function(el) {
    el.style.fontFamily = "Lato";
});

getElementsByTagName("*") will access the browser's list of all elements in the document, if it already has one; getElementsByTagName("*")将访问浏览器中文档中所有元素的列表(如果已有的话)。 and build it if not. 并建立它,如果没有。 (This is in contrast to querySelectorAll , which is required to always build a new one.) Then we loop over it by borrowing forEach from Array.prototype . (这与总是创建一个新的querySelectorAll相反。)然后我们通过从Array.prototype借用forEach遍历它。 (See the "array-like objects" part of my answer here for details.) (有关详细信息,请参见我的答案的“类似数组的对象”部分。)

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

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