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

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

document.body.onselectstart = function () { 
    return false; 
};
 
// 或
document.body.onmousedown = function () { 
    return false; 
}

 

阻止特定区域的内容被选中

    var elem = document.getElementById('elemId');
    elem.onselectstart = function () {
        return false;
    };

 使用 CSS 控制样式阻止内容被选中

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

 

.unselect {
    -webkit-user-select: none; 
    -moz-user-select: none;    
    -khtml-user-select: none;  
    -ms-user-select: none;    
 
    /* 以下两个属性目前并未支持,写在这里为了减少风险 */
    -o-user-select: none;
    user-select: none;  

清除选中

 

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();
    }       
}

 

posted @ 2018-08-24 10:52  Shimily  阅读(425)  评论(0)    收藏  举报