js操作css特效
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="util.js" ></script>
<script>
function test(){
var con=$("#container");
var childs=getChildNodes(con);
for(var i =0;i<childs.length;i++){
childs[i].οnmοuseοver=function(){
//函数中的中间变量 只有在运行的时候才去找值 定义时候 只起一个占位作用 跟this
//alert(childs);
//alert(i);
// childs[i].style.backgroundColor="red"; 不行
this.style.backgroundColor="red";//谁调用我 我就指向谁 这里是 每个标签对象进行调用 指向标签对象
}
childs[i].οnmοuseοut=function(){
this.style.backgroundColor="white";
}
}
}
</script>
</head>
<body>
<div id="container">
<div>aaaaaaaaaaaaaaaa</div>
<div>bbbbbbbbbbbbbbbb</div>
<div>ccccccccccccccccc</div>
<div>dddddddddddddddd</div>
</div>
<input type="button" value="test" οnclick="test()" />
</body>
</html>
js代码:
/**
*
* @param idOrName 如果传入id 前面加上# 如果传入name 直接传入
* @returns {*} 返回元素节点 如果没找到 返回null
*/
function $(idOrName){
var obj=null;
if(idOrName){
if(idOrName.charAt(0)=="#"){
obj=document.getElementById(idOrName.substring(1));
}else{
obj=document.getElementsByName(idOrName);
}
}
return obj;
}
/**
*
* @param parentNode 父节点
* @returns {Array} 所有的元素子节点
*/
function getChildNodes(parentNode){
var childs=parentNode.childNodes;
var newChilds=[];
for(var i=0;i<childs.length;i++){
if(childs[i].nodeType==1){
newChilds.push(childs[i]);
}
}
return newChilds;
}
/**
*
* @param parentNode 父节点
* @returns {*|Node} 第一个元素节点
*/
function getFirstChild(parentNode){
var firstChild=parentNode.firstChild;
if(firstChild.nodeType==3){
firstChild=firstChild.nextSibling;
}
return firstChild;
}
/**
*
* @param parentNode 父节点
* @returns {*|Node} 最后一个元素节点
*/
function getLastChild(parentNode){
var lastChild=parentNode.lastChild;
if(lastChild.nodeType==3){
lastChild=lastChild.previousSibling;
}
return lastChild;
}
/**
*
* @param node 元素节点
* @returns {*|Node} 返回下一个兄弟元素节点
*/
function getNextSibling(node){
var nextNode=node.nextSibling;
if(nextNode.nodeType==3){
nextNode=nextNode.nextSibling;
}
return nextNode;
}
/**
*
* @param node 元素节点
* @returns {*|Node} 返回前一个兄弟元素节点
*/
function getPreviousSibling(node){
var preNode=node.previousSibling;
if(preNode.nodeType==3){
preNode=preNode.previousSibling;
}
return preNode;
}