原声js 的兼容(屏幕尺寸、事件处理程序、阻止事件冒泡、事件目标等等)

来源:互联网 发布:58同城网络推广 编辑:程序博客网 时间:2024/05/17 08:54

1、事件处理程序
function addEvent(obj, type, fn) { //添加事件兼容
if (obj.addEventListener) {
obj.addEventListener(type, fn,false);
} else if (obj.attachEvent) {
obj.attachEvent(‘on’ + type, fn);
}else{
obj[‘on’+type]=fn;
}
}

function removeEvent(obj, type, fn) { //移除事件兼容
if (obj.removeEventListener) {
obj.removeEventListener(type, fn,false);
} else if (obj.detachEvent) {
obj.detachEvent(‘on’ + type, fn);
}else{
obj[‘on’+type]=null;
}
}
2、阻止事件冒泡
//不冒泡的事件:blur focus load unload
//阻止冒泡:标准浏览器:event.stopPropagation()
//ie :event.cancelBubble = true
function stopPropagation() {
if(event || event.stopPropagation){
event.stopPropagation();
}else{
event.cancelBubble = true;
}
}
3、跨浏览器兼容 阻止事件的默认行为
function preDef(evt) {
var e = evt || window.event;
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
PS:虽然return false;可以实现这个功能,但有漏洞;第一:必须写到最后,这样导致中间的代码执行后,有可能执行不到return false;第二:return false写到最前那么之后的自定义操作就失效了。
4、判断是否为当前对象的id
var targetId = event.target?event.target.id :event.srcElement.id;

5、客户端屏幕尺寸:
function client() {
if(window.innerHeight !=null){
return {
height:window.innerHeight,
width:window.innerWidth
}
}else if(document.compatMode ===”CSS1Compat”){
return {
height:document.documentElement.clientHeight,
width:document.documentElement.clientWidth
}
}else{
return {
height:document.body.clientHeight,
width:document.body.clientWidth
}
}
}
笔记:window.screen.width __得到电脑分辨率
6、选择文本
if(window.getSelection){
txt = window.getSelection().toString(); //w3c
}else{
txt = document.selection.createRange().text; //ie
}
7、得到计算后的样式
function curStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return window.getComputedStyle(obj,null)[attr];
}
}

0 0
原创粉丝点击