87,987
社区成员
发帖
与我相关
我的任务
分享
//$_custom.js
function $_custom(fun)
{
document.onreadystatechange = function()
{
if (document.readyState == "complete")
{
fun();
}
}
}
function $(val){
if(val.indexOf("#")==0)
{
var ob=new Array();
var obj=document.getElementById(val.substring(1));
ob.push(obj);
custom.call(ob);
return ob;
}
if(val.indexOf(".")==0)
{
var obj=document.getElementsByTagName("*");
var ob=new Array();
for(var x in obj)
{
if(obj[x].className==val.substring(1))
{
obj2=obj[x];
ob.push(obj2);
}
}
custom.call(ob);
return ob;
}
}
var custom=function(){
var actions=["click","blur","focus","mouseout","mouseover","change"];
//样式处理
this.css=function(param){
for(var i = 0;i < this.length;i++)
{
for(var key in param)
{
this[i].style[key]=param[key];
}
}
};
var _this=this;
//函数处理
(function(){
for(var k in actions){
var _o=actions[k];
_this[_o]= function(){
var _oo=_o;
return function(fun)
{
for(var i = 0;i < _this.length;i++)
{
_this[i]["on"+_oo]=function(event)
{
fun(event);
}
}
}
}(_o);
}
})(actions);
//还原javascript基本写法
this.revert=function(){
if(_this.length==1)
{
return _this[0];
}
else
{
alert('Does not support!');
console.log('Does not support!');
}
};
//模拟鼠标事件
this.similar=function(actions){
if(document.all) {
_this[0][actions]();
}
else {
var e = document.createEvent("MouseEvents");
e.initMouseEvent(actions, true, true);
_this[0].dispatchEvent(e);
}
};
//绑定事件
this.bind=function(actions,fun){
if(document.all) {
for(var i = 0;i < _this.length;i++)
_this[i].attachEvent("on"+actions,function(){fun.call(_this[i])});
}else{
for(var i = 0;i < _this.length;i++)
_this[i].addEventListener(actions,fun);
}
}
}
<script type="text/javascript" src="$_custom.js"></script>
<script type="text/javascript">
$_custom(function(){
$("#sp").css({width:"100px",height:"100px",border:"1px solid red"});
$(".sp2").css({width:"100px",height:"100px",border:"1px solid red"});
})
</script>
<div id="sp">test</div>
<div class="sp2">test</div>
<div class="sp2">test</div>
//支持的事件在actions数组里拓展
$("#sp").click(function(){
alert('test');
})
$("#sp").revert().style.display='none';
$("#sp").click(function(){
alert('clicked');
})
$("#sp").similar("click");
//这样刚进入网页即运行点击事件了
$("#sp").bind("click",function(){
alert('you click');
})
$("#sp").click(function(){
alert(event.x);
})
//event参数可直接支持调用,可以阻止事件冒泡等,不信试试吧
