《Javascript 高级程序设计(第三版)》笔记0x14 DOM2和DOM3:样式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/funkstill/article/details/85035217

目录

样式

     访问元素的样式

       DOM 样式属性和方法

        计算的样式

    操作样式表

        CSS 规则

        创建规则

        删除规则

    元素大小

        偏移量(offset dimension)

         客户区大小(client dimension)

         滚动大小(scroll dimension)

         确定元素大小


样式

        在 HTML 中定义样式的方式有 3 种:通过<link/>元素包含外部样式表文件、使用<style/>元素定义嵌入式样式,以及使用 style 特性定义针对特定元素的样式。

//确定浏览器是否支持 DOM2 级定义的 CSS 能力
var supportsDOM2CSS = document.implementation.hasFeature("CSS", "2.0");
var supportsDOM2CSS2 = document.implementation.hasFeature("CSS2", "2.0");

     访问元素的样式

        在 style 特性中指定的任何 CSS 属性都将表现为这个style 对象的相应属性。对于使用短划线(分隔不同的词汇,例如 background-image)的 CSS 属性名,必须将其转换成驼峰大小写形式,才能通过 JavaScript 来访问。

var myDiv = document.getElementById("myDiv");
//设置背景颜色
myDiv.style.backgroundColor = "red";
//改变大小
myDiv.style.width = "100px";
myDiv.style.height = "200px";
//指定边框
myDiv.style.border = "1px solid black";

       DOM 样式属性和方法

        “DOM2 级样式”规范还为 style 对象定义了一些属性和方法。这些属性和方法在提供元素的 style特性值的同时,也可以修改样式。

    cssText:通过它能够访问到 style 特性中的 CSS 代码。
    length:应用给元素的 CSS 属性的数量。
    parentRule:表示 CSS 信息的 CSSRule 对象。
    getPropertyCSSValue(propertyName):返回包含给定属性值的 CSSValue 对象。
    getPropertyPriority(propertyName):如给定的属性使用了!important 设置,则返回"important";否则,返回空字符串。
    getPropertyValue(propertyName):返回给定属性的字符串值。
    item(index):返回给定位置的 CSS 属性的名称。
    removeProperty(propertyName):从样式中删除给定属性。
    setProperty(propertyName,value,priority):将给定属性设置为相应的值,并加上优先权标志("important"或者一个空字符串)。

myDiv.style.cssText = "width: 25px; height: 100px; background-color: green";
alert(myDiv.style.cssText);

//设计 length 属性的目的,就是将其与 item()方法配套使用,以便迭代在元素中定义的 CSS 属性。
for (var i=0, len=myDiv.style.length; i < len; i++){
	alert(myDiv.style[i]); //或者 myDiv.style.item(i)
}

//可以在 getPropertyValue()中使用取得的属性名进一步取得属性的值
var prop, value, i, len;
for (i=0, len=myDiv.style.length; i < len; i++){
	prop = myDiv.style[i]; //或者 myDiv.style.item(i)
	value = myDiv.style.getPropertyValue(prop);
	alert(prop + " : " + value);
}

var prop, value, i, len;
for (i=0, len=myDiv.style.length; i < len; i++){
	prop = myDiv.style[i]; //或者 myDiv.style.item(i)
	value = myDiv.style.getPropertyCSSValue(prop);
	alert(prop + " : " + value.cssText + " (" + value.cssValueType + ")");
}

myDiv.style.removeProperty("border");

        计算的样式

        “DOM2 级样式”增强了 document.defaultView,提供了getComputedStyle()方法。这个方法接受两个参数:要取得计算样式的元素和一个伪元素字符串(例如":after")。如果不需要伪元素信息,第二个参数可以是 null。getComputedStyle()方法返回一个 CSSStyleDeclaration 对象(与 style 属性的类型相同),其中包含当前元素的所有计算的样式。

<!DOCTYPE html>
<html>
	<head>
		<title>Computed Styles Example</title>
		<style type="text/css">
			#myDiv {
			background-color: blue;
			width: 100px;
			height: 200px;
			}
		</style>
	</head>
	<body>
		<div id="myDiv" style="background-color: red; border: 1px solid black"></div>
	</body>
</html>
var myDiv = document.getElementById("myDiv");
var computedStyle = document.defaultView.getComputedStyle(myDiv, null);
alert(computedStyle.backgroundColor); // "red"
alert(computedStyle.width); // "100px"
alert(computedStyle.height); // "200px"
alert(computedStyle.border); // 在某些浏览器中是"1px solid black"

    操作样式表

       CSSStyleSheet 类型表示的是样式表,包括通过<link>元素包含的样式表和在<style>元素中定义的样式表。

var sheet = null;
for (var i=0, len=document.styleSheets.length; i < len; i++){
	sheet = document.styleSheets[i];
	alert(sheet.href);
}

//在不同浏览器中都能取得样式表对象
function getStyleSheet(element){
	return element.sheet || element.styleSheet;
}
//取得第一个<link/>元素引入的样式表
var link = document.getElementsByTagName("link")[0];
var sheet = getStylesheet(link);

        CSS 规则

    CSSRule 对象表示样式表中的每一条规则。实际上, CSSRule 是一个供其他多种类型继承的基类a型,其中最常见的就是 CSSStyleRule 类型,表示样式信息(其他规则还有@import、 @font-face、@page 和@charset,但这些规则很少有必要通过脚本来访问)。

    CSSStyleRule 对象包含下列属性。
    cssText:返回整条规则对应的文本。由于浏览器对样式表的内部处理方式不同,返回的文本可能会与样式表中实际的文本不一样; Safari 始终都会将文本转换成全部小写。 IE 不支持这个属性。
    parentRule:如果当前规则是导入的规则,这个属性引用的就是导入规则;否则,这个值为null。 IE 不支持这个属性。
    parentStyleSheet:当前规则所属的样式表。 IE 不支持这个属性。
    selectorText:返回当前规则的选择符文本。由于浏览器对样式表的内部处理方式不同,返回的文本可能会与样式表中实际的文本不一样(例如, Safari 3 之前的版本始终会将文本转换成全部小写)。在 Firefox、 Safari、 Chrome 和 IE 中这个属性是只读的。 Opera 允许修改 selectorText。
    style:一个 CSSStyleDeclaration 对象,可以通过它设置和取得规则中特定的样式值。
    type:表示规则类型的常量值。对于样式规则,这个值是 1。 IE 不支持这个属性。

/*
div.box {
	background-color: blue;
	width: 100px;
	height: 200px;
}
*/

//获取
var sheet = document.styleSheets[0];
var rules = sheet.cssRules || sheet.rules; //取得规则列表
var rule = rules[0]; //取得第一条规则
alert(rule.selectorText); //"div.box"
alert(rule.style.cssText); //完整的 CSS 代码
alert(rule.style.backgroundColor); //"blue"
alert(rule.style.width); //"100px"
alert(rule.style.height); //"200px"

//设置
var sheet = document.styleSheets[0];
var rules = sheet.cssRules || sheet.rules; //取得规则列表
var rule = rules[0]; //取得第一条规则
rule.style.backgroundColor = "red"

        创建规则

sheet.insertRule("body { background-color: silver }", 0); //DOM 方法

sheet.addRule("body", "background-color: silver", 0); //仅对 IE 有效

function insertRule(sheet, selectorText, cssText, position){
	if (sheet.insertRule){
		sheet.insertRule(selectorText + "{" + cssText + "}", position);
	} else if (sheet.addRule){
		sheet.addRule(selectorText, cssText, position);
	}
}

insertRule(document.styleSheets[0], "body", "background-color: silver", 0);

        删除规则

sheet.deleteRule(0); //DOM 方法

sheet.removeRule(0); //仅对 IE 有效

function deleteRule(sheet, index){
	if (sheet.deleteRule){
		sheet.deleteRule(index);
	} else if (sheet.removeRule){
		sheet.removeRule(index);
	}
}
deleteRule(document.styleSheets[0], 0);

    元素大小

        偏移量(offset dimension)

    元素的可见大小由其高度、宽度决定,包括所有内边距、滚动条和边框大小(注意,不包括外边距)。通过下列 4 个属性可以取得元素的偏移量。
    offsetHeight:元素在垂直方向上占用的空间大小,以像素计。包括元素的高度、(可见的)水平滚动条的高度、上边框高度和下边框高度。
    offsetWidth:元素在水平方向上占用的空间大小,以像素计。包括元素的宽度、(可见的)垂直滚动条的宽度、左边框宽度和右边框宽度。
    offsetLeft:元素的左外边框至包含元素的左内边框之间的像素距离。
    offsetTop:元素的上外边框至包含元素的上内边框之间的像素距离

/*要想知道某个元素在页面上的偏移量,将这个元素的 offsetLeft 和 offsetTop 与其 offsetParent
的相同属性相加,如此循环直至根元素,就可以得到一个基本准确的值。*/
function getElementLeft(element){
	var actualLeft = element.offsetLeft;
	var current = element.offsetParent;
	while (current !== null){
		actualLeft += current.offsetLeft;
		current = current.offsetParent;
	}
	return actualLeft;
}

function getElementTop(element){
	var actualTop = element.offsetTop;
	var current = element.offsetParent;
	while (current !== null){
		actualTop += current. offsetTop;
		current = current.offsetParent;
	}
	return actualTop;
}

         客户区大小(client dimension)

function getViewport(){
	if (document.compatMode == "BackCompat"){
		return {
			width: document.body.clientWidth,
			height: document.body.clientHeight
		};
	} else {
		return {
			width: document.documentElement.clientWidth,
			height: document.documentElement.clientHeight
		};
	}
}

         滚动大小(scroll dimension)

/*
在确定文档的总高度时(包括基于视口的最小高度时),必须取得 scrollWidth/clientWidth 和
scrollHeight/clientHeight 中的最大值,才能保证在跨浏览器的环境下得到精确的结果。
*/
var docHeight = Math.max(document.documentElement.scrollHeight,
	document.documentElement.clientHeight);
var docWidth = Math.max(document.documentElement.scrollWidth,
	document.documentElement.clientWidth);

//检测元素是否位于顶部
function scrollToTop(element){
	if (element.scrollTop != 0){
		element.scrollTop = 0;
	}
}

         确定元素大小

function getBoundingClientRect(element){
	var scrollTop = document.documentElement.scrollTop;
	var scrollLeft = document.documentElement.scrollLeft;
	if (element.getBoundingClientRect){
		if (typeof arguments.callee.offset != "number"){
			var temp = document.createElement("div");
			temp.style.cssText = "position:absolute;left:0;top:0;";
			document.body.appendChild(temp);
			arguments.callee.offset = -temp.getBoundingClientRect().top - scrollTop;
			document.body.removeChild(temp);
			temp = null;
		}
		var rect = element.getBoundingClientRect();
		var offset = arguments.callee.offset;
		return {
			left: rect.left + offset,
			right: rect.right + offset,
			top: rect.top + offset,
			bottom: rect.bottom + offset
		};
	} else {
		var actualLeft = getElementLeft(element);
		var actualTop = getElementTop(element);
		return {
			left: actualLeft - scrollLeft,
			right: actualLeft + element.offsetWidth - scrollLeft,
			top: actualTop - scrollTop,
			bottom: actualTop + element.offsetHeight - scrollTop
		}
	}
}

猜你喜欢

转载自blog.csdn.net/funkstill/article/details/85035217