h5 禁止选中 阻止默认事件

本文介绍如何使用CSS属性user-select防止元素被选中,以及如何在JavaScript中阻止默认上下文菜单事件,包括兼容不同浏览器的方法。

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

1. 禁止选中
<html onselectstart="return false">
            #box{
                overflow: hidden;
                position: relative;
                width: 700px;
                height: 540px;
                background: antiquewhite;
                border: 1px solid deeppink;
                margin: 50px auto;
                padding: 0 20px;
                user-select: none;           ------------添加
                -moz-user-select: -moz-none; ------------添加
                -ms-user-select: none;       ------------添加
            }

两个地方添加 内容

 

2. 阻止默认事件

    //直接绑定
            //主流浏览器可以用e.preventDefault();  也可以用return false;
            //IE浏览器只能用return false;
            document.oncontextmenu = function (e) {
                //e = e || window.event;
                //e.preventDefault();
                alert( 1 );
                return false;
            }
     //注册事件 -- 主流
            //不能通过return false来阻止默认事件
            document.addEventListener("contextmenu" , function (e) {
                e.preventDefault(); //可以
                alert( 1 );
                return false;       //不可以
            } , false );

            //注册事件 -- IE8 及 以下
            //只能通过return fasle来阻止默认事件
            document.attachEvent("oncontextmenu" , function () {
                //window.event.preventDefault();
                alert( 1 );
                return false;       //可以
            })

        //兼容写法
            function fn(e) {
                e = e || window.event;

                //code……

                e.preventDefault && e.preventDefault();---------
                return false;                          ---------
            }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值