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

本文介绍了一系列前端开发中事件处理的兼容性解决方案,包括事件监听、取消监听、阻止冒泡、阻止默认行为等核心功能,并展示了如何获取元素样式及屏幕尺寸。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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];
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值