javascript改样式_使用JavaScript向样式表添加规则

javascript改样式

Update:Rewrites made to accurately represent current practice for stylesheet injection.

更新:进行重写以准确表示样式表注入的当前实践。

Since we're using so much JavaScript in our web applications these days, we're looking for more ways to keep them fast.  We use event delegation to keep event listening efficient, we use function debouncing to limit the number a times a given method can be used, use JavaScript loaders to load only the resources we need, and so on.  Another way we can make our pages efficient and fast is to dynamically add and remove styles directly to a stylesheet instead of constantly querying the DOM for elements and applying styles.  Here's how it works!

由于这些天我们在Web应用程序中使用了太多JavaScript,因此我们正在寻找更多方法来保持它们的快速运行。 我们使用事件委托来保持事件侦听的效率,使用函数反跳来限制给定方法可以使用的次数,使用JavaScript加载器仅加载我们需要的资源,依此类推。 使页面高效和快速的另一种方法是直接向样式表中动态添加和删除样式,而不是不断向DOM查询元素和应用样式。 运作方式如下!

获取样式表 (Getting the Stylesheet)

Which stylesheet you add the rules to is up to you.  If you have a specific stylesheet in mind, you can add an ID to the LINK or STYLE element within your page HTML and get the CSSStyleSheet object by referencing the element's sheet property.  The stylesheets can be found in the document.styleSheets object:

您可以将规则添加到哪个样式表中。 如果您有特定的样式表,则可以在页面HTML内的LINKSTYLE元素中添加ID ,并通过引用元素的sheet属性来获取CSSStyleSheet对象。 可以在document.styleSheets对象中找到样式表:


var sheets = document.styleSheets; // returns an Array-like StyleSheetList

/*
Returns:  

StyleSheetList {0: CSSStyleSheet, 1: CSSStyleSheet, 2: CSSStyleSheet, 3: CSSStyleSheet, 4: CSSStyleSheet, 5: CSSStyleSheet, 6: CSSStyleSheet, 7: CSSStyleSheet, 8: CSSStyleSheet, 9: CSSStyleSheet, 10: CSSStyleSheet, 11: CSSStyleSheet, 12: CSSStyleSheet, 13: CSSStyleSheet, 14: CSSStyleSheet, 15: CSSStyleSheet, length: 16, item: function}
*/

// Grab the first sheet, regardless of media
var sheet = document.styleSheets[0];


One important consideration is the media of the stylesheet -- you want to ensure you aren't adding rules to a print stylesheet when you expect the styles to display on screen.  A CSSStyleSheet object does have informational properties for you to peruse:

一个重要的考虑因素是样式表的media -您希望确保在希望样式显示在屏幕上时不会在打印样式表中添加规则。 CSSStyleSheet对象确实具有信息属性供您细读:


// Get info about the first stylesheet
console.log(document.styleSheets[0]);

/*
Returns:  

CSSStyleSheet
	cssRules: CSSRuleList
	disabled: false
	href: "https://davidwalsh.name/somesheet.css"
	media: MediaList
	ownerNode: link
	ownerRule: null
	parentStyleSheet: null
	rules: CSSRuleList
	title: null
	type: "text/css"
*/

// Get the media type
console.log(document.styleSheets[0].media.mediaText)
/*
Returns:
	"all" or "print" or whichever media is used for this stylesheet
*/
 

In any event, there are many ways to grab a stylesheet to attach style rules to.

无论如何,有很多方法可以获取样式表以将样式规则附加到该样式表。

创建一个新的样式表 (Creating a New Stylesheet)

In many cases, it may just be best to create a new STYLE element for your dynamic rules.  This is quite easy:

在许多情况下,最好为动态规则创建一个新的STYLE元素。 这很简单:


var sheet = (function() {
	// Create the <style> tag
	var style = document.createElement("style");

	// Add a media (and/or media query) here if you'd like!
	// style.setAttribute("media", "screen")
	// style.setAttribute("media", "only screen and (max-width : 1024px)")

	// WebKit hack :(
	style.appendChild(document.createTextNode(""));

	// Add the <style> element to the page
	document.head.appendChild(style);

	return style.sheet;
})();


Unfortunately WebKit requires a hack to properly get things going but all we care about is having that sheet.

不幸的是,WebKit需要骇客才能使事情正常进行,但我们所关心的只是拥有该表。

插入规则 (Inserting Rules)

Stylesheets have an insertRule method which isn't available in earlier IE's but is now the standard for rule injection.  The insertRule requires that you write the entire CSS rule just as you would in a stylesheet:

样式表具有insertRule方法,该方法在早期的IE中不可用,但现在是规则注入的标准。 insertRule要求您像编写样式表一样编写整个CSS规则:


sheet.insertRule("header { float: left; opacity: 0.8; }", 1);


This method may seem a bit ugly for a JavaScript API but that's how it works. The second argument, the index, represents the index at which to insert the rule. This is helpful so that you can insert the same rule/code and define which wins out. The default for index is -1, which means the end of the collection.  For extra/lazy control, you may add !important to rules to avoid problems with the index.

对于JavaScript API而言,此方法似乎有点难看,但这就是它的工作原理。 第二个参数index表示要插入规则的索引。 这很有用,因此您可以插入相同的规则/代码并定义胜出的规则/代码。 index的默认值为-1 ,表示集合的结尾。 对于额外/惰性控制,您可以在规则中添加!important以避免索引出现问题。

添加规则-非标准addRule (Adding Rules - Nonstandard addRule)

CSSStyleSheet objects have an addRule method which allows you to register CSS rules within the stylesheet.  The addRule method accepts three arguments:  the selector, the second the CSS code for the rule, and the third is the zero-based integer index representing the style position (in relation to styles of the same selector):

CSSStyleSheet对象具有addRule方法,该方法允许您在样式表中注册CSS规则。 addRule方法接受三个参数:选择器,第二个是规则CSS代码,第三个是从零开始的整数索引,表示样式位置(相对于同一选择器的样式):


sheet.addRule("#myList li", "float: left; background: red !important;", 1);


addRule calls return a result of -1 in all cases -- it really doesn't represent anything.

在所有情况下, addRule调用均返回-1的结果-实际上它不代表任何内容。

Remember that the advantage here is that elements added from the page automatically have the styles applied to them; i.e. you wont have to add them to elements as they're injected into the page.  Efficient!

请记住,这里的优点是从页面添加的元素会自动应用样式。 即,您无需将它们添加到元素中,因为它们已被注入到页面中。 高效!

安全应用规则 (Safely Applying Rules)

Since browser support for insertRule isn't as global, it's best to create a wrapping function to do the rule application.  Here's a quick and dirty method:

由于浏览器对insertRule支持不是全局的,因此最好创建一个包装函数来执行规则应用程序。 这是一种快速而肮脏的方法:


function addCSSRule(sheet, selector, rules, index) {
	if("insertRule" in sheet) {
		sheet.insertRule(selector + "{" + rules + "}", index);
	}
	else if("addRule" in sheet) {
		sheet.addRule(selector, rules, index);
	}
}

// Use it!
addCSSRule(document.styleSheets[0], "header", "float: left");


This utility method should cover all cases of new style application.  If you are nervous about applying variable styles across your app, it's reasonable to wrap the inner code of this method in a try{}catch(e){} block.

此实用程序方法应涵盖所有新型应用程序。 如果您对在应用程序中应用可变样式感到紧张,则可以将这种方法的内部代码包装在try{}catch(e){}块中,这是合理的。

插入媒体查询规则 (Inserting Rules for Media Queries)

Media query-specific rules can be added in one of two ways. The first way is through the standard insertRule method:

可以使用以下两种方式之一添加特定于媒体查询的规则。 第一种方法是通过标准的insertRule方法:


sheet.insertRule("@media only screen and (max-width : 1140px) { header { display: none; } }");

Of course since IE hasn't always supported insertRule, the other method is creating a STYLE element with the proper media attribute, then adding styles to that new stylesheet. This may require juggling multiple STYLE elements, but that's easy enough. I would probably create an object with media queries as indexes, and create/retrieve them that way.

当然,由于IE并不总是支持insertRule ,因此另一种方法是使用适当的media属性创建一个STYLE元素,然后将样式添加到该新样式表中。 这可能需要处理多个STYLE元素,但这很容易。 我可能会创建一个以媒体查询为索引的对象,然后以这种方式创建/检索它们。

Dynamically adding rules to stylesheets is efficient and easier than you may think.  Keep this strategy in mind on your next big app, as it may save you work in both code and element processing.

向样式表中动态添加规则比您想象的要高效和容易。 在您的下一个大型应用程序中牢记这一策略,因为它可以节省您在代码和元素处理方面的工作。

翻译自: https://davidwalsh.name/add-rules-stylesheets

javascript改样式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值