日期:2014-05-16 浏览次数:20482 次
function addEvent(obj,type,fn){
if(obj.attachEvent){
obj.attachEvent('on'+type,function(){
fn.call(obj);
});
}else{
obj.addEventListener(type,fn,false) ;
}
}
function getByClass(oParent, sClass) //class选择器
{
var aEle=oParent.getElementsByTagName('*');
var aResult=[];
var re=new RegExp('\\b'+sClass+'\\b', 'i');
var i=0;
for(i=0;i<aEle.length;i++)
{
//if(aEle[i].className==sClass)
//if(aEle[i].className.search(sClass)!=-1)
if(re.test(aEle[i].className))
{
aResult.push(aEle[i]);
}
}
return aResult;
}
function getStyle(obj,attr){ //获取非行间样式
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return window.getComputedStyle(obj,false)[attr];
}
}
function ZQuery(vArg){
this.elements=[];
switch (typeof vArg){
case 'function':
addEvent(window,'load',vArg);
break;
case 'string':
switch (vArg.charAt(0)){
case '#':
var obj=document.getElementById(vArg.substring(1));
this.elements.push(obj);
break;
case '.':
this.elements=getByClass(document,vArg.substring(1));
break;
default:
this.elements=document.getElementsByTagName(vArg);
}
break;
}
}
ZQuery.prototype.css=function(attr,value){
if(arguments.length==2){
var i=0;
for(i=0;i<this.elements.length;i++){
this.elements[i].style[attr]=value;
}
}else{
return getStyle(this.elements[0],attr);
}
}
ZQuery.prototype.hover=function(fnover,fnout){
var i=0;
for(i=0;i<this.elements.length;i++){
addEvent(this.elements[i],'mouseover',fnover);
addEvent(this.elements[i],'mouseout',fnout);
}
}
function $(vArg){
return new ZQuery(vArg);
}
前台调用的代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="js.js"></script>
<script>
$(function(){
$('div').hover(function(){
//$(this).css('background','#2A3F00');无效
$('div').css('background','#2A3F00');//正常
},function(){
//$(this).css('background','#F0F');无效
$('div').css('background','#F0F');//正常
})
})
</script>
<style>
div{ width:100px; height:100px; background:#F0F;}
</style>
</head>
<body>
<div></div>
</body>
</html>