获取单个对象节点
// 获取单个对象 document.getElementById("box");
// 获取多个节点
var x = document.getElementsByClassName("box");
nodename属性
// nodename属性 // nodename // nodevalue // 元素节点的nodename和便签名相同 // 属性节点的nodename和属性的名称相同 // 文本节点的nodename永远是#text // 元素节点的nodeValue是 undefined 和null // 文本节点的nodeValue是文本自身的值 // 属性节点的nodeValue是属性的值
节点对象的常用属性
var a = document.getElementById('w'); //childNodes获取所有的元素标签 console.log(a.childNodes); //获取第一个子节点 a.firstChild; //获取最后一个子节点 a.lastChild; // 获取父级节点 a.parentNode; //获取写一个同级节点 a.nextSibling; //获取上一个同级节点 a.previousSibling
// 获取单个对象
// document.getElementById("box");
对节点的增删改
// 创建节点 var newNode = document.createElement('p'); // 设置节点的属性 newNode.setAttribute("class","bianq"); //插入字符串 也可以插入标签 newNode.innerHTML = '<a href = "#">彭伟</a>'; //获取父级节点 var oDiv = document.getElementById('box'); // 插入节点 oDiv.appendChild(newNode); //插入字符串 也可以插入标签 newNode.innerHTML = '<a href = "#">彭伟</a>'; // 删除节点 oDiv.removeChild(o); // 替换节点 rreplaceChild(新节点,被替换的节点); // 替换节点 oDiv.replaceChild(newNode3,o);
newNode = null; //释放对象
设置样式
// 获取节点 var oDiv = document.getElementById('box'); // 设置样式 oDiv.style.width = "200px"; oDiv.style.height = "100px"; oDiv.style.backgroundColor = "green"; //通过控制属性类名来控制样式 oDiv.setAttribute('class','di');
单击事件onclick
// 获取节点 var oDiv = document.getElementById('box'); oDiv.setAttribute("class","di"); // 单击事件 oDiv.onclick = function(){ alert("我被单击了,艹"); } //或者 var add = function (){ this.style.backgroundColor = 'red'; } oDiv.onclick = add;
鼠标离开和悬浮事件onmouseover,onmouseout
// 获取节点 var oDiv = document.getElementById('box'); oDiv.setAttribute("class","di"); // 鼠标悬浮和离开事件 // 鼠标悬浮事件 oDiv.onmouseover = function(){ this.style.backgroundColor = 'red'; } //鼠标离开事件 oDiv.onmouseout = function(){ this.style.backgroundColor = 'orange'; }
光标聚焦和失去焦点 onfocus,onblur
//光标聚焦事件 usrname.onfocus = function(){ console.log("请输入用户名"); newNode.innerHTML ="请输入用户名"; newNode.setAttribute("class","text"); usrname.parentNode.appendChild(newNode); } // 失去焦点 usrname.onblur = function(){ newNode.innerHTML ="请输入正确的用户名"; newNode.setAttribute("class","di"); usrname.parentNode.appendChild(newNode); }
内容被选中,提交,实时监控事件onselect,onchange,oninput
var textareas = document.getElementsByTagName("textarea")[0]; var inputs = document.getElementsByTagName("input")[0]; // 内容被选中事件 textareas.onselect = function(){ console.log("我特么被选中了"); } // 内容提交事件 inputs.onchange = function(){ console.log("我特么也被选中了"); } // 内容实时监控事件 inputs.oninput = function(){ console.log("卧槽你大爷") }
窗口加载 事件window.onlode
main = function(){ } // 窗口加载事件 window.onload = main;