JavaScript中操作对象的属性

1.操作对象的属性

注意:

标签属性与DOM对象属性的相应关系:

绝大部分2者是同样的。如:imgobj.src属性相应<img src="" >中src属性,但也有例外,如<div class="main" >中,操作class属性用divobj.className。

CSS属性与DOM对象属性的相应关系:

1. 两者通过obj.style.css属性名 相相应   如:obj.style.width。

2.假设CSS属性带有横线,如border-top-style  ,则把横线去掉并将横线后字母大写 。  如:obj.style.borderTopStyle。


样例:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html"; charset="utf-8"/>
	<title></title>
</head>
<style type="text/css">
	.test1{
		background: red;
	}
	.test2{
		background: green;
	}
</style>
<body>
<div class="test1"  onclick="a();" style="200px; height:200px; border-bottom:1px solid">
	点击div,使其背景色红绿交替,宽高添加5px,下边框增粗1px;

</div>
<script type="text/javascript">
	function a(){
		var div = document.getElementsByTagName('div')[0];
		if(div.className.indexOf('test1')>=0){
			div.className = 'test2';
		}else{
			div.className = 'test1';
		}

		div.style.width = parseInt(div.style.width)+10+'px';
		div.style.height = parseInt(div.style.height)+10+'px';
		div.style.borderBottomWidth = parseInt(div.style.borderBottomWidth)+1+'px';
	}
</script>
</body>
</html>


获取对象在内存中计算后的样式:

用obj.currenStyle 和window.getComputedStyle()获取。

注意:仅仅有IE和Opera支持使用currentStyle获取HTML Element的计算后的样式,其它浏览器不支持。标准的浏览器用getComputedStyle,IE9以上也支持getComputedStyle。


window.getComputedStyle(obj,伪元素);

參数说明:1.第一个參数为要获取计算后的样式的目标元素

                    2.第二个參数为期望的伪元素,如:‘:after’。‘:first-letter’等。一般设为 null。

function getStyle(obj,attr){
		 return obj.currentStyle ?

obj.currentStyle[attr] : getComputedStyle(obj,null)[attr]; } //考虑兼容性,封装函数。



上述样例改动后的版本号:改动后的版本号将 CSS 的style属性放到了body之外。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html"; charset="utf-8"/>
	<title></title>
</head>
<style type="text/css">
	div{
		 200px;
		height: 200px;
		border-bottom: 1px solid black;
	}
	.test1{
		background: red;
	}
	.test2{
		background: green;
	}
</style>
<body>
<div class="test1"  onclick="a();" >
	点击div,使其背景色红绿交替,宽高添加5px,下边框增粗1px;

</div>
<script type="text/javascript">
	function getStyle(obj,attr){
		 return obj.currentStyle ?

obj.currentStyle[attr] : getComputedStyle(obj,null)[attr]; } //考虑兼容性,封装函数。

function a(){ var div = document.getElementsByTagName('div')[0]; if(div.className.indexOf('test1')>=0){ div.className = 'test2'; }else{ div.className = 'test1'; } //alert(getStyle(div,'width')); //return; div.style.width = parseInt(getStyle(div,'width'))+10+'px'; div.style.height = parseInt(getStyle(div,'height'))+10+'px'; div.style.borderBottomWidth = parseInt(getStyle(div,'borderBottomWidth'))+1+'px'; } </script> </body> </html>






原文地址:https://www.cnblogs.com/jzssuanfa/p/6956438.html