改变JS中所有元素的Css

Change Css for All elements from JS

本文关键字:元素 Css JS 改变      更新时间:2023-09-26

我试图改变jQuery对话框的字体家族从一个小显示设置面板。这些方法我都试过了,但都没有用:

$('#orderHolder').style.fontFamily='Bookman Old Style';
$('.ui-dialog-content').style.fontFamily='Bookman Old Style';
$('.ui-widget-content').style.fontFamily='Bookman Old Style';
$('#orderHolder').css("font-family", "Bookman Old Style';
$('*').css('font-family', 'Bookman Old Style'); //this is what I'm after 

(#orderHolder是包含对话框内容的div)

我发现


*{ font-family: 'Bookman Old Style'; }

在。css文件中工作得很好,整体效果是我想要的。

那么,如何在javascript中选择所有元素的样式?

jQuery:

$('*').css('font-family','Bookman Old Style');
javascript:

document.querySelectorAll('*').style.fontFamily = 'Bookman Old Style';

更新:

实际上当你使用querySelectorAll:

时你需要遍历所有元素
var el = document.querySelectorAll('*');
for(var i=0;i<el.length;i++){
  el[i].style.fontFamily = 'Bookman Old Style';
}

但是在使用星号选择器时不需要遍历所有元素,您可以使用querySelector:

document.querySelector('*').style.fontFamily='Bookman Old Style';

但是如果你将font-family设置为body那么你的字体将会被所有元素继承,所以只适用于body

您可能需要将其设置为重要样式:此外,如果有任何其他字体族,请删除它。试试下面的代码

CSS中:

*{
font-family: 'Bookman Old Style' !important;
}
在jquery:

$('#content').find('*').css("font-family","'Bookman Old Style'");
我发现

*{
   font-family: 'Bookman Old Style';
}

在。css文件中工作得很好,整体效果是我想要的。

在这种情况下,由于显然没有将font-family应用于更具体的选择器,因此最好的选择是使用以下规则向文档添加style元素:

$("<style>* { font-family: 'Bookman Old Style'; }</style>").appendTo("head");

或:

$("<style>body { font-family: 'Bookman Old Style'; }</style>").appendTo("head");

…如果他们都继承了body的风格

前面的答案都不适合我。但这:

document.head.innerHTML = document.head.innerHTML + '<style type="text/css">*{font-family: Georgia !important }</style>'

**应用以下方法**


1. jquery$('*').css('fontFamily','Times New Roman');

2. java脚本document.querySelectorAll('*').style.fontFamily = 'Times New Roman';

3. css*{ font-family: 'Times New Roman'; }