700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > CSS详解(Element中style属性 伪元素 StyleSheet对象)

CSS详解(Element中style属性 伪元素 StyleSheet对象)

时间:2021-01-03 20:32:40

相关推荐

CSS详解(Element中style属性 伪元素 StyleSheet对象)

目录

1 HTML元素的style属性

2 Element节点的style属性

2.1 基本用法

2.2 cssText属性

2.3 CSS模块的侦测

2.4 setPropertyValue(),getPropertyValue(),removeProperty()

3 CSS伪元素

4 StyleSheet对象

4.1 获取样式表

4.2 属性

4.2.1 media属性

4.2.2 disabled属性

4.2.3 href属性

4.2.4 title属性

4.2.5 type属性

4.2.6 parentStyleSheet属性

4.2.7 ownerNode属性

4.2.8 cssRules属性

4.3 insertRule(),deleteRule()

4.4 添加样式表

CSS与JavaScript是两个有着明确分工的领域,前者负责页面的视觉效果,后者负责与用户的行为互动。但是,它们毕竟同属网页开发的前端,因此不可避免有着交叉和互相配合。本节介绍如果通过JavaScript操作CSS。

1 HTML元素的style属性

操作Element节点的CSS样式,最简单的方法之一就是使用节点对象的getAttribute方法、setAttribute方法和removeAttribute方法,读写或删除HTML元素的style属性。

div.setAttribute('style','background-color:red;'+ 'border:1px solid black;');

2 Element节点的style属性

2.1 基本用法

Element节点本身还提供style属性,用来操作CSS样式

style属性指向一个对象,用来读写页面元素的行内CSS样式。

var divStyle = document.querySelector('div').style;divStyle.backgroundColor = 'red';divStyle.border = '1px solid black';divStyle.width = '100px';divStyle.height = '100px';divStyle.backgroundColor // reddivStyle.border // 1px solid blackdivStyle.height // 100pxdivStyle.width // 100px

从上面代码可以看到,style对象的属性与CSS规则名一一对应,但是需要改写。具体规则是将横杠从CSS属性名中去除,然后将横杠后的第一个字母大写,比如background-color写成backgroundColor。如果CSS属性名是JavaScript保留字,则规则名之前需要加上字符串“css”,比如float写成cssFloat。

注意,style对象的属性值都是字符串,而且包括单位。所以,divStyle.width不能设置为100,而要设置为'100px'。

2.2 cssText属性

style对象的cssText可以用来读写或删除整个style属性。

divStyle.cssText = 'background-color:red;'+ 'border:1px solid black;'+ 'height:100px;'+ 'width:100px;';

注意,cssText对应的是HTML元素的style属性,所以不用改写CSS属性名。

2.3 CSS模块的侦测

CSS的规格发展太快,新的模块层出不穷。不同浏览器的不同版本,对CSS模块的支持情况都不一样。有时候,需要知道当前浏览器是否支持某个模块,这就叫做“CSS模块的侦测”。

一个比较普遍适用的方法是,判断某个DOM元素的style对象的某个属性值是否为字符串

typeof element.style.animationName === 'string';typeof element.style.transform === 'string';

如果该CSS属性确实存在,会返回一个字符串。即使该属性实际上并未设置,也会返回一个空字符串。如果该属性不存在,则会返回undefined。

document.body.style['maxWidth'] // ""document.body.style['maximumWidth'] // undefined

需要注意的是,不管CSS属性名带不带连词线,style对象都会显示该属性存在

document.body.style['backgroundColor'] // ""document.body.style['background-color'] // ""

所有浏览器都能用这个方法,但是使用的时候,需要把不同浏览器的CSS规则前缀也考虑进去。

var content = document.getElementById("content");typeof content.style['webkitAnimation'] === 'string'

这种侦测方法可以写成一个函数。

function isPropertySupported(property){if (property in document.body.style) return true;var prefixes = ['Moz', 'Webkit', 'O', 'ms', 'Khtml'];var prefProperty = property.charAt(0).toUpperCase() + property.substr(1);for(var i=0; i<prefixes.length; i++){if((prefixes[i] + prefProperty) in document.body.style) return true;}return false;}isPropertySupported('background-clip')// true

2.4 setPropertyValue(),getPropertyValue(),removeProperty()

style对象的以下三个方法,用来读写行内CSS规则

setPropertyValue(propertyName,value):设置某个CSS属性。getPropertyValue(propertyName):读取某个CSS属性。removeProperty(propertyName):删除某个CSS属性。

这三个方法的第一个参数,都是CSS属性名,且不用改写连词线

divStyle.setPropertyValue('background-color','red');divStyle.getPropertyValue('background-color');divStyle.removeProperty('background-color');

3 CSS伪元素

CSS伪元素是通过CSS向DOM添加的元素,主要方法是通过“:before”和“:after”选择器生成伪元素,然后用content属性指定伪元素的内容。

":before" 伪元素可以在元素的内容前面插入新内容。":after" 伪元素可以在元素的内容之后插入新内容。

以如下HTML代码为例。

<div id="test">Test content</div>

CSS添加伪元素的写法如下。

#test:before {content: 'Before ';color: #FF0;}

DOM节点的style对象无法读写伪元素的样式,这时就要用到window对象的getComputedStyle方法。JavaScript获取伪元素,可以使用下面的方法。

var test = document.querySelector('#test');var result = window.getComputedStyle(test, ':before').content;var color = window.getComputedStyle(test, ':before').color;

此外,也可以使用window.getComputedStyle对象的getPropertyValue方法,获取伪元素的属性。

var result = window.getComputedStyle(test, ':before').getPropertyValue('content');var color = window.getComputedStyle(test, ':before').getPropertyValue('color');

4 StyleSheet对象

4.1 获取样式表

StyleSheet对象代表网页的一张样式表,它包括link节点加载的样式表和style节点内嵌的样式表。

document对象的styleSheets属性,可以返回当前页面的所有StyleSheet对象(即所有样式表)。它是一个类似数组的对象。

var sheets = document.styleSheets;var sheet = document.styleSheets[0];

此外,link节点和style节点的sheet属性,也可以获取StyleSheet对象。

// HTML代码为// <link id="linkElement" href="http://path/to/stylesheet">// <style id="styleElement">// body{font-size: 1.2 rem;}// </style>// 等同于document.styleSheets[0]document.querySelector('#linkElement').sheet// 等同于document.styleSheets[1]document.querySelector('#styleElement').sheet

4.2 属性

StyleSheet对象有以下属性。

4.2.1 media属性

media属性表示这个样式表是用于屏幕(screen),还是用于打印(print),或两者都适用(all)。该属性只读,默认值是screen。

document.styleSheets[0].media.mediaText// "all"

4.2.2 disabled属性

disabled属性用于打开或关闭一张样式表。

document.querySelector('#linkElement').disabled = true;

disabled属性只能在JavaScript中设置,不能在html语句中设置。

4.2.3 href属性

href属性是只读属性,返回StyleSheet对象连接的样式表地址。对于内嵌的style节点,该属性等于null。

document.styleSheets[0].href

4.2.4 title属性

title属性返回StyleSheet对象的title值。

4.2.5 type属性

type属性返回StyleSheet对象的type值,通常是text/css。

document.styleSheets[0].type // "text/css"

4.2.6 parentStyleSheet属性

CSS的@import命令允许在样式表中加载其他样式表。parentStyleSheet属性返回包括了当前样式表的那张样式表。如果当前样式表是顶层样式表,则该属性返回null。

if (stylesheet.parentStyleSheet) {sheet = stylesheet.parentStyleSheet;} else {sheet = stylesheet;}

4.2.7 ownerNode属性

ownerNode属性返回StyleSheet对象所在的DOM节点,通常是<link>或<style>。对于那些由其他样式表引用的样式表,该属性为null。

// HTML代码为// <link rel="StyleSheet" href="example.css" type="text/css" />document.styleSheets[0].ownerNode // [object HTMLLinkElement]

4.2.8 cssRules属性

cssRules属性指向一个类似数组的对象,里面每一个成员就是当前样式表的一条CSS规则。使用该规则的cssText属性,可以得到CSS规则对应的字符串。

var sheet = document.querySelector('#styleElement').sheet;sheet.cssRules[0].cssText// "body { background-color: red; margin: 20px; }"sheet.cssRules[1].cssText// "p { line-height: 1.4em; color: blue; }"

每条CSS规则还有一个style属性,指向一个对象,用来读写具体的CSS命令。

styleSheet.cssRules[0].style.color = 'red';styleSheet.cssRules[1].style.color = 'purple';

4.3 insertRule(),deleteRule()

insertRule方法用于在当前样式表的cssRules对象插入CSS规则,deleteRule方法用于删除cssRules对象的CSS规则。

var sheet = document.querySelector('#styleElement').sheet;sheet.insertRule('#blanc { color:white }', 0);sheet.insertRule('p { color:red }',1);sheet.deleteRule(1);

insertRule方法的第一个参数是表示CSS规则的字符串,第二个参数是该规则在cssRules对象的插入位置deleteRule方法的参数是该条规则在cssRules对象中的位置。

IE 9开始支持insertRule方法,在此之前都使用addRule方法。addRule的写法与insertRule略有不同,接受三个参数。

sheet.addRule('p','color:red',1);

上面代码将一条CSS语句插入p选择器所有语句的第二位。最后一个参数默认为-1,即新增语句插在所有语句的最后。

4.4 添加样式表

添加样式表有两种方式。一种是添加一张内置样式表,即在文档中添加一个<style>节点。

var style = document.createElement('style');style.setAttribute('media', 'screen');// 或者style.setAttribute("media", "@media only screen and (max-width : 1024px)");style.innerHTML = 'body{color:red}';// 或者sheet.insertRule("header { float: left; opacity: 0.8; }", 1);document.head.appendChild(style);

另一种是添加外部样式表,即在文档中添加一个link节点,然后将href属性指向外部样式表的URL。

var linkElm = document.createElement('link');linkElm.setAttribute('rel', 'sty规则lesheet');linkElm.setAttribute('type', 'text/css');linkElm.setAttribute('href', 'reset-min.css');document.head.appendChild(linkElm);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。