您的位置:首页 > 编程语言

读dom编程艺术总结——操作dom元素

2014-05-29 11:16 459 查看
一.获取元素节点三种方法

document.getElementById('id1');

document.getElementsByTagName(“标签的名字例如:ul”)——得到所有的标签

html5新增的方法:

document.getElementByClassName('id1');

可以这样封装:

function tag(name, elem) {

    return (elem || document).getElementsByTagName(name);

}

二.获取和设置样式

这两个方法只能对元素节点使用

obj.getAttribute("样式名")

obj.setAttribute("样式名","样式值")

还有一个简单的方法obj.className = "类名" 这样可以直接命名字符串;

可以这样封装:

function hasAttribute(elem, name) {

    return elem.getAttribute(name) != null;

};

样式表有三种方式:
内嵌样式(inline Style) :是写在html标签里面的。
内部样式(internal Style Sheet):是写在HTML的头部。
外联样式表(External Style Sheet):是用link链接到外部css文件。

js里获取样式表的几种语法:

用法  作用
 style   obj.style.att 只能获取或修改内嵌样式

注意:增改top、left等,IE里直接写数值,Firefox等要加”px”
 currentStyle   obj.currentStyle.att

 obj.currentStyle[att]

当arr为字符串传参时,带中括号 [ ] 的格式可以识别,而.arr格式不能识别。
 能获取(仅获取)三种方式的样式(仅IE),只读模式
 getComputedStyle   window.getComputedStyle(obj, pseudoElt)[att]

window.getComputedStyle(obj, pseudoElt).att

window.getComputedStyle(obj, pseudoElt).getPropertyValue(att)

window.getComputedStyle(obj, pseudoElt).getPropertyCSSValue(att)

document.defaultView.getComputedStyle(obj,pseudoElt)[att]

document.defaultView.getComputedStyle(obj,pseudoElt).att

document.defaultView.getComputedStyle(obj,pseudoElt)

.getPropertyValue(att)

document.defaultView.getComputedStyle(obj,pseudoElt)

.getPropertyCSSValue(att)
 能获取(仅获取)三种方式的样式(除IE)

 要修改就直接用obj.style.arr
getComputedStyle的语法可为以上八种,严格来说,带上getPropertyValue或getPropertyCSSValue才算是标准吧。其中pseudoElt是指伪元素,如:after, :before, :marker, :line-marker之类的,如果不用伪类,则填null就可以了。getPropertyValue和getPropertyCSSValue有什么区别呢,getPropertyValue返回的是一个string,而getPropertyCSSValue返回的是一个CSS2Properties对象

复合样式:background backgroundcolor

单一样式:height

三.

obj.childNodes 返回所有子元素(三种节点:元素节点,属性节点,文本节点)

用obj.nodeType 判断元素类型

四.创建插入删除 dom节点

创建
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: