zoukankan      html  css  js  c++  java
  • 防止内容被选中

    在开发拖动效果时,有一个非常恼人的地方要处理时,就是拖动时,文本被选中蓝色一片,容易造成用户分心,有损用户体验。通常我们是用下面代码来清理selection:

    
                 if(window.getSelection){//w3c
                    window.getSelection().removeAllRanges();
                  }else  if(document.selection){
                    document.selection.empty();//IE
                  }
    

    但这东西在谷歌浏览器中,快速拖动还是会出现蓝色(人家的渲染效率就是高),另外,每拖动一像素就清理一次,这频繁的调用对于一些旧式浏览器可不是好事。最近研究CSS3,发现user-select这个东西,终于搞定这问题了。

    首先,我们要检测浏览器是否支持它,FF与webkit系浏览器是支持,IE9与opera11是不支持。

    
    //by 司徒正美
    //http://www.cnblogs.com/rubylouvre/archive/2011/03/28/1998223.html
          var getStyleName= (function(){
            var prefixes = ['', '-ms-','-moz-', '-webkit-', '-khtml-', '-o-'];
            var reg_cap = /-([a-z])/g;
            function getStyleName(css, el) {
              el = el || document.documentElement;
              var style = el.style,test;
              for (var i=0, l=prefixes.length; i < l; i++) {
                test = (prefixes[i] + css).replace(reg_cap,function($0,$1){
                  return $1.toUpperCase();
                });
                if(test in style){
                  return test;
                }
              }
              return null;
            }
            return getStyleName;
          })();
          alert(getStyleName("user-select"))
    

    对于不支持的浏览器,我们可以借助它们的一些私有属性与事件,如unselectable,onselectstart。当拖动时,我们把它们绑定在文档对象上就行了。

                 if(typeof userSelect === "string"){
                    return document.documentElement.style[userSelect] = "none";
                  }
                  document.unselectable  = "on";
                  document.onselectstart = function(){
                    return false;
                  }
    

    当拖动结束时,我们再让文档变回可选择模式,注意一些值的变化,都是很奇特的名字。

                  if(typeof userSelect === "string"){
                    return document.documentElement.style[userSelect] = "text";
                  }
                  document.unselectable  = "off";
                  document.onselectstart = null;
    

    具体应用见下:

  • 相关阅读:
    测试方案写作要点
    [loadrunner]通过检查点判定事务是否成功
    【面试】如何进行自我介绍
    【nginx网站性能优化篇(1)】gzip压缩与expire浏览器缓存
    【nginx运维基础(6)】Nginx的Rewrite语法详解
    【PHPsocket编程专题(实战篇①)】php-socket通信演示
    【Linux高频命令专题(22)】gzip
    【nginx运维基础(5)】Nginx的location攻略
    【Linux高频命令专题(21)】df
    【PHPsocket编程专题(理论篇)】初步理解TCP/IP、Http、Socket.md
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/2040121.html
Copyright © 2011-2022 走看看