ITeye博客

使用user-select禁止网页选择文字

小丑鱼0703 · 2015-04-08 09:50 · css · Web前端 · Markdown

http://www.wufangbo.com/css-jin-zhi-xuan-ze/

user-select有两个值:

none:用户不能选择文本 text:用户可以选择文本

注意:user-select不是一个W3C的CSS标准属性,浏览器支持的不完整,需要对每种浏览器进行调整。

body{
  -moz-user-select: none; /*火狐*/
  -webkit-user-select: none; /*webkit浏览器*/
  -ms-user-select: none; /*IE10*/
  -khtml-user-select: none; /*早期浏览器*/
  user-select: none;
}

IE6-9还没发现相关的CSS属性,禁止网页选择文字但是文本框中的文字可以选中,使用js实现:

//IE6-9
if (typeof(document.onselectstart) != "undefined") {       
    // IE下禁止元素被选取       
    document.onselectstart = function (event){
        if(event.target.tagName!="INPUT"){
            return false;
        }
    }      
} else {
    // 高级浏览器下禁止元素被选取的变通办法       
    document.onmousedown = function (event){
        if(event.target.tagName!="INPUT"){
            return false;
        }
    }      
    document.onmouseup = function(event){
        if(event.target.tagName!="INPUT"){
            return false;
        }
    }       
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。