• 防止内容被选中


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

    具体应用见下:

  • 相关阅读:
    现状和措施
    Nginx http升级到https
    搭建 git 服务器
    Vue + Springboot 开发的简单的用户管理系统
    Vue中的button事件
    Mvc多级Views目录 asp.net mvc4 路由重写及 修改view 的寻找视图的规则
    asp.net mvc 多级目录结构
    Asp.net下使用HttpModule模拟Filter,实现权限控制
    JavaScript事件冒泡简介及应用
    Rhino Mock
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/2040121.html
Copyright © 2020-2023  润新知