节点常用三种节点:元素节点,属性节点和文本节点
判断节点类型:nodeType 对应上面123
获取元素节点的方法:getElementById(" id名"),getElementsByTagName(元素名”),getElementsByIdClassName(“类名”)
获取和设置属性:getAttribute(),setAtrribute("属性名”,“值”)
创建元素节点:doucument.createElement(“p”)方法
插入节点树:parent.appendChild(插入的节点)
节点关系:childNodes,firstChild,lastChild
访问文本节点:nodeValue 注意获取文本节点时,文本节点一般是上级节点的第一个子元素,例如<P>中 p.firstChild.nodeValue
创建文本节点:document.createTextNode(text) document.body.appendChild()
插入元素:parent.insertBefore(newElement,targetElement)
只能在元素前面插入,构造函数在目标元素后插入insertAfter
function insertAfter(new,target){
var parent=target.parentNode;
if(parent.lastChild==target){ //如果目标元素是父元素的最后一个元素直接插入,因为appenChild是放在最后
parent.appendChild(new);
}else{
parent.insertBefore(new.target.nextSlibling) //如果不是最后一个元素,调用nextSibling
}
}
CSS和DOM:
css名驼峰法
para.style.font="14px serif"
className属性: element.classname
设置元素的ClassName属性:elem.className="someClass";
css专门调用下一个元素节点,
function getNext(node){
if(node.nodeType==1){
return node;
}
if(node.nextSibling){ //如果存在下一个节点,则再次调用这个函数
return getNext(node.nextSibling);
}
return null;
}
动画相关
ani=setTimeout(函数,时间)
clearTimeout(ani)
JavaScript中建议的最佳实践:
- javascript中的平稳退化:不支持js时仍能顺利浏览网站,例如:
window.open(url,name,features) features新窗口的各种属性 高度宽度禁用的浏览功能等
<a href="https://www.baidu.com" οnclick="PopUp(this.href);return false;">some text</a>
function popUp(url){window.open(url,"popup".width="320,height=480");
2. 分离JavaScript
3.对象检测:if(!document.getElementById || getElementsByTagName) return false;
4.减少访问DOM
5.压缩脚本
window.onload事件两种方法:
window.οnlοad=function(){
firstFunction();
secondFunction();
}
另一种方法,具有弹性
function addLoadEvent(func){
var oldοnlοad=window.onload;
if(typeof window.onload!="function"){ //如果没有绑定函数,就把函数绑定到window.onload上
window.οnlοad=func;
}else{
window.οnlοad=function(){
oldonload(); //如果绑定了函数,就把新函数追加到现有的末尾,旧的仍要添加;
func();
}
}