您当前的位置: 首页 > 

顺其自然~

暂无认证

  • 2浏览

    0关注

    1317博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

使用 JS 阻止网页的内容被选中

顺其自然~ 发布时间:2022-04-25 15:14:15 ,浏览量:2

使用 JS 阻止整个网页的内容被选中
document.body.onselectstart = function () { 
    return false; 
};
 
// 或
document.body.onmousedown = function () { 
    return false; 
}

原理:重写onselectstart(),onmousedown,并且返回false,阻止事件发生后继续调用默认处理函数进行处理。

阻止特定区域的内容被选中
var elem = document.getElementById('elemId');
elem.onselectstart = function () {
    return false;
};
使用 CSS 控制样式阻止内容被选中

仅支持非 IE10 以下的浏览器。IE9 以下请使用 onselectstart="return false;" 的方式来实现。

*{ 
 -webkit-touch-callout:none; /*系统默认菜单被禁用*/ 
 -webkit-user-select:none; /*webkit浏览器*/ 
 -khtml-user-select:none; /*早期浏览器*/ 
 -moz-user-select:none;/*火狐*/ 
 -ms-user-select:none; /*IE10*/ 
 user-select:none; 
} 
input{ 
 -webkit-user-select:auto; /*webkit浏览器*/  
}
textarea{
 -webkit-user-select:auto; /*webkit浏览器*/
}
清除选中
function clearSelections () {
    if (window.getSelector) {
        // 获取选中
        var selection = window.getSelection();
        // 清除选中
        selection.removeAllRanges();
    } else if (document.selection && document.selection.empty) {
       // 兼容 IE8 以下,但 IE9+ 以上同样可用
        document.selection.empty();
        // 或使用 clear() 方法
        // document.selection.clear();
    }       
}

参考:

https://www.cnblogs.com/shimily/articles/9528504.html

Vue实现页面内容禁止选中功能_Johnny_yellowboy的博客-CSDN博客_vue禁止选中

关注
打赏
1662339380
查看更多评论
立即登录/注册

微信扫码登录

0.0437s