1.实现jquery中addClass()和removeClass()的功能:
function addClass( obj, className){
if( obj.className ==''){
obj.className = className;
}else{
var arrClassName = obj.className.split(' ');
if(arrIndexOf( arrClassName, className) ==-1){
obj.className += ' '+className;
}
}
}
function removeClass( obj, className){
if(obj.className !=''){
var arrClassName = obj.className.split(' ');
if(arrIndexOf( arrClassName,className )!=-1 ){
arrClassName.splice(arrIndexOf( arrClassName,className ),1);
obj.className = arrClassName.join(' ');
}
}
}
//判断要添加的类是否已存在
function arrIndexOf(arr,v){
for(var i=0;i<arr.length;i++){
if(arr[i]==v){
return i;
}
}
return -1;
}
2.写一个placeholder的兼容函数,value为“请输入内容”。当获取焦点时清空,失去焦点且为空时恢复
<input type="text" value="请输入内容" id="text1" />
<script>
var oText1=document.getElementById("text1");
oText1.onfocus=function(){
if(this.value=="请输入内容"){
this.value='';
}
}
oText1.onblur=function(){
if(this.value==''){
this.value=="请输入内容";
}
}
</script>
</body>
2.实现了事件绑定函数:
function bind(obj,evname,fn){
if(obj.addEventListener){
obj.addEventListener(evname,fn,false);
}else{
obj.attachEvent('on'+evname,function(){
fn.call(obj);//调用call方法,在IE下将this从指向window改为指向当前对象
}
)}
}
3.实现事件解绑:
function removBind(obj,evname,fn,bl){
if(obj.removeEventListener){
obj.removeEventListener(evname,fn,bl)
}else{obj.detachEvent('on'+evname,fn,function(){
fn.call(obj);
})
}
}
4.事件侦听器:
var Event = {
// 页面加载完成后
readyEvent : function (fn) {
if (fn == null) {
fn = document;
}
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = fn ;
}else{
window.onload = function () {
oldonload();
fn();
}
};
},
//添加事件
addEvent : function(element, type, hander) {
if (element.addEventListener) { //非IE
//事件类型、需要执行的函数、是否捕捉
element.addEventListener(type, hander, false);
}else if(element.attachEvent){ //IE
element.attachEvent('on' + type,function () {
hander.call(element);
})
}else{
element['on' +type] = hander;
};
},
//移除事件
removeEvent : function (element, type, hander) {
if (element.removeEventListener) {
element.removeEventListener(type, handler, false)
}else if (element.attachEvent) {
element.attachEvent('on' + type, hander);
}else{
element['on' + type] = null;
};
},
//阻止事件
stopPropagation : function (event) {
if (event.stopPropagation) {
event.stopPropagation(); //W3C标准
}else{
event.canceBubble = true; //IE
};
},
//取消默认事件
preventDefault : function (event) {
if (event.preventDefault) {
event.preventDefault();
};
},
//获取事件目标
getTarget : function (event) {
return event.target|event.srcElement;
},
//获取event对象的引用,取到事件的所有信息,确保随时能使用event;
getEvent:function (event) {
var event = event || window.event;
if (!event) {
var c = this.getEvent.caller;
while(!c){
event = c.arguments[0];
if (event && Event == ev.constructor) {
break;
};
c = c.caller;
}
};
return event;
}
}
网友评论