JavaScript中操作对象的属性

来源:互联网 发布:品茗网络计划破解版 编辑:程序博客网 时间:2024/05/20 21:58

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="width: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{width: 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>





0 0
原创粉丝点击