rubylouvre

防止内容被选中

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

具体应用见下:

分类:

技术点:

相关文章:

  • 2022-01-10
  • 2021-12-12
  • 2021-10-04
  • 2021-08-07
  • 2021-11-05
  • 2021-12-19
  • 2021-06-11
  • 2022-12-23
猜你喜欢
  • 2021-08-14
  • 2022-01-18
  • 2021-11-13
  • 2022-12-23
  • 2022-12-23
  • 2021-11-29
  • 2021-12-24
相关资源
相似解决方案