search
HomeBackend DevelopmentPHP Tutorial使用JavaScript创建新样式表和新样式规则_php实例

如今的这个年代,流行在Web页面上使用了大量的JavaScript,我们需要寻找各种方式来优化它们,使它们更快。我们使用事件委托来让事件监听器更有效率,使用降频技术来限定某些方法的使用次数,使用各种JavaScript加载器来动态加载我们需要的资源,等等。另外一种让页面更高效、更敏捷的方法是动态的添加或移除样式表里的样式,而不需要去查询DOM元素,对每个元素做样式调整。下面我们就来看看如何使用这种技术!

捕获样式表

你的页面上可能引用了不只一个的样式文件,你可以选择其中的一个。如果你指定了某个,你可以在HTML页面中的LINK 和 STYLE标签上加入ID来进行区别,获取CSSStyleSheet对象,它存放在document.styleSheets对象里。


var sheets = document.styleSheets; // 返回一个StyleSheetList数组

/*
返回: 

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
}
*/

// 找到你想要修改的样式表
var sheet = document.styleSheets[0];


一个重要的需要注意的事情是样式表的media属性——如果你不小心,当想往屏幕显示使用的样式表里做修改操作时,你也许会错误的修改了用于打印(print)时使用的样式表。CSSStyleSheet对象里有各种属性信息,需要时你可以从中获取。


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

/*
返回结果: 

CSSStyleSheet
 cssRules: CSSRuleList
 disabled: false
 href: "http://davidwalsh.name/somesheet.css?1.1.2"
 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
*/


有很多方法都可以让你捕获一个样式表,往里面添加新样式规则。

创建一个新的样式表

大多数时候,最好的方法是创建一个新的STYLE元素,动态的往里面添加规则。非常简单:

var sheet = (function() {
 // Create the <style> tag
 var style = document.createElement("style");
 
 // 如果你愿意的话,可以添加media属性 (或 media query) 
 // style.setAttribute("media", "screen")
 // style.setAttribute("media", "@media only screen and (max-width : 1024px)")
 
 // WebKit 补丁 
 style.appendChild(document.createTextNode(""));
 
 // Add the <style> element to the page
 document.head.appendChild(style);
 
 return style.sheet;
})();

不幸的是,WebKit类型的浏览器需求做一点点小修改,才能让上面的代码正确的运行,但不管怎样,我们获得了想要的sheet。

添加样式规则 – 标准的addRule方法

CSSStyleSheet对象里有一个addRule方法,它可以接受3个参数:选择器、样式规则的CSS代码和一个整数,这个整数用来指示样式表的位置(相对于同样的选择器):

sheet.addRule("#myList li", "float: left; background: red !important;", 1);
位置缺省值为-1,表示放在最后。为了进行额外的控制,或偷懒的写法,你可以在规则里添加!important来消除位置引起的问题。调用addRule会返回-1——它什么都不表示。

你会发现,这种技术的优势在于,它可以动态的往页面上添加样式规则,并应用它们;你不必对每个元素进行操作,浏览器会自动应用这些规则。高效吧!

新增样式规则

CSSStyleSheet对象里还有一个insertRule方法,但在早期的IE里是没有这个方法的。insertRule方法把addRule方法的前两个参数混合到了一起:

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

这个方法看起来很丑陋,但无疑也是非常有用的。

安全的应用样式规则

因为并不是所有的浏览器都支持insertRule,最好我们做一些封装来确保代码的有效执行。下面就是一个很简单的封装方法:

function addCSSRule(sheet, selector, rules, index) {
 if(sheet.insertRule) {
 sheet.insertRule(selector + "{" + rules + "}", index);
 }
 else {
 sheet.addRule(selector, rules, index);
 }
}
 
// Use it!
addCSSRule(document.styleSheets[0], "header", "float: left");

这个方法可以应对各种情况。如果你想把这个方法里的代码单独拿出来使用,最好用try{}catch(e){}把它们包起来。

为媒体查询(Media Queries)增加样式规则

有两个方法可以为特定的媒体查询增加样式规则。第一种是通过标准的insertRule方法:

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

因为老式的IE不支持insertRule,我们可以使用另外一种方法,就是创建一个STYLE元素,赋予它正确的media属性,然后往里面添加新的样式规则。这种方式会增加额外的STYLE元素,但十分的简单。

我认为动态的往样式表里添加样式规则是一种十分高效而且简单的技术。记住在你的下一个应用里试一下这种技术,它会省了你很多功夫。

以上就是使用JavaScript创建新样式表和新样式规则_php实例的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)