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


    pretty-girl {
        -webkit-user-select: none;     
    }

    可是!可是!不是每个浏览器都可以不忧桑!!!那就只能请脚本大王出山了。

    阻止选中

    有时候,我们需要禁止用户选中一些文本区域,这时候可以直接通过让 onselectstart 事件 return false 来实现。

    使用 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;  
    }

    user-select: auto; => 用户可以选中元素中的内容

    user-select: none; => 用户不可选中元素中的内容

    user-select: text; => 用户可以选中元素中的文字

    目前这个 user-select 兼容 Chrome 6+、Firefox、IE 10+、Opera 15+、Safari 3.1+。

    需要注意的是,这个 user-select 还带浏览器厂商前缀,意味着她们还是非标准的,将来可能会改变。在生产环境中要慎用。

    清除选中

    有时候用户选中文字进行复制后,我们使用手动的方式进行选中的清除。

    使用 JS 清除选中

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

    使用 CSS 清除选中

    不考虑低版本 IE 的情况下,我们简单给选中元素添加以上 .unselect 的样式即可。

  • 相关阅读:
    ms日期函数大全
    Sql server char,nchar,varchar与Nvarchar的区别
    clientX pageX
    jswindow对象的方法和属性资料
    Asp.Net中不修改IIS实现URL重写,支持任意扩展名及无扩展名
    该行已经属于另一个表的解决方法
    dopostBack机制(转)
    js触发asp.net的Button的Onclick事件
    Value、ReadString、ReadContentAsString、ReadElementContentAsString 区别
    有关元素元素位置的属性
  • 原文地址:https://www.cnblogs.com/tanghongbo/p/4208385.html
Copyright © 2020-2023  润新知