JavaScript简单实现鼠标拖动选择功能


Posted in Javascript onMarch 06, 2014
<style><!--
body{padding-top:50px;padding-left:100px;padding-right:150px;}
  .fileDiv{float:left;width:100px;height:100px;text-align:center;line-height:100px;font-size:12px;border:1px solid #cccccc;margin-right:10px;margin-bottom:10px;}
  .seled{border:1px solid #ff0000;background-color:#D6DFF7;}
--></style>
<script type="text/javascript">// <![CDATA[
Array.prototype.remove = function( item ){
  for( var i = 0 ; i < this.length ; i++ ){
   if( item == this[i] )
    break;
  }
  if( i == this.length )
   return;
  for( var j = i ; j < this.length - 1 ; j++ ){
   this[ j ] = this[ j + 1 ];
  }
  this.length--;
  } String.prototype.replaceAll = function (AFindText,ARepText){ raRegExp = new RegExp(AFindText,"g"); return this.replace(raRegExp,ARepText);}
 function getAllChildren(e) {
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  if (!document.getElementsByTagName) {
    return new Array();
  }
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName  &&  element.nodeName.toLowerCase() != tagName) {
        return new Array();
      }
      currentContext = new Array(element);
      continue; 
    }
    if (token.indexOf('.') > -1) {
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className  &&  found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue;
    }
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; 
      switch (attrOperator) {
        case '=':
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|':
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^':
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': 
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': 
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue;
    }
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}
 function addEvent(eventType,eventFunc,eventObj){
    eventObj = eventObj || document;
    if(window.attachEvent)  eventObj.attachEvent("on"+eventType,eventFunc);
     if(window.addEventListener) eventObj.addEventListener(eventType,eventFunc,false);
  }
function clearEventBubble(evt){
   evt = evt || window.event;
    if (evt.stopPropagation) evt.stopPropagation(); else evt.cancelBubble = true; 
     if (evt.preventDefault)  evt.preventDefault();  else evt.returnValue = false;
}
function posXY(event){
 event = event || window.event;
 var posX = event.pageX || (event.clientX +
         (document.documentElement.scrollLeft || document.body.scrollLeft));
 var posY = event.pageY || (event.clientY +
         (document.documentElement.scrollTop || document.body.scrollTop));
 return {x:posX, y:posY};
}
 var _selectedRegions = [];
 function RegionSelect(selRegionProp){
   this.regions =[];
   var _regions = document.getElementsBySelector(selRegionProp["region"]);
   if(_regions  &&  _regions.length > 0){
    var _self = this;
     for(var i=0; i< _regions.length;i++){
       _regions[i].onmousedown = function(){
         var evt = window.event || arguments[0];
         if(!evt.shiftKey  &&  !evt.ctrlKey){
          // 清空所有select样式
          _self.clearSelections(_regions);
          this.className += " "+_self.selectedClass;
          // 清空selected数组,并加入当前select中的元素
          _selectedRegions = [];
          _selectedRegions.push(this);
         }else{
          if(this.className.indexOf(_self.selectedClass) == -1){
            this.className += " "+_self.selectedClass;
            _selectedRegions.push(this);
          }else{
            this.className = this.className.replaceAll(_self.selectedClass,"");
            _selectedRegions.remove(this);
          }
         }
         clearEventBubble(evt);
       }
       this.regions.push(_regions[i]);
     }
   }
   this.selectedClass = selRegionProp["selectedClass"];
   this.selectedRegion = [];
   this.selectDiv = null;
   this.startX = null;
   this.startY = null;
 }
 RegionSelect.prototype.select = function(){
  var _self = this;
  addEvent("mousedown",function(){
    var evt = window.event || arguments[0];
    _self.onBeforeSelect(evt);
    clearEventBubble(evt);
  },document);
  addEvent("mousemove",function(){
    var evt = window.event || arguments[0];
    _self.onSelect(evt);
    clearEventBubble(evt);
  },document);
  addEvent("mouseup",function(){
    _self.onEnd();
  },document);
 }
 RegionSelect.prototype.onBeforeSelect = function(evt){
  if(!document.getElementById("selContainer")){
     this.selectDiv = document.createElement("div");
     this.selectDiv.style.cssText = "position:absolute;width:0px;height:0px;font-size:0px;margin:0px;padding:0px;border:1px dashed #0099FF;background-color:#C3D5ED;z-index:1000;filter:alpha(opacity:60);opacity:0.6;display:none;";
     this.selectDiv.id = "selContainer";
     document.body.appendChild(this.selectDiv);
   }else{
     this.selectDiv = document.getElementById("selContainer");
   }
   this.startX = posXY(evt).x;
   this.startY = posXY(evt).y;
   this.isSelect = true;
 }
 RegionSelect.prototype.onSelect = function(evt){
    var _self = this;
    if(_self.isSelect){
      if(_self.selectDiv.style.display == "none") _self.selectDiv.style.display = "";
      var posX = posXY(evt).x;
      var poxY = posXY(evt).y;
      _self.selectDiv.style.left   = Math.min(posX, this.startX);
     _self.selectDiv.style.top    = Math.min(poxY, this.startY);
     _self.selectDiv.style.width  = Math.abs(posX - this.startX);
     _self.selectDiv.style.height = Math.abs(poxY - this.startY);  
     var regionList = _self.regions;
     for(var i=0; i< regionList.length; i++){
       var r = regionList[i], sr = _self.innerRegion(_self.selectDiv,r);
       if(sr  &&  r.className.indexOf(_self.selectedClass) == -1){
          r.className = r.className + " "+_self.selectedClass; 
          _selectedRegions.push(r);
       }else if(!sr  &&  r.className.indexOf(_self.selectedClass) != -1){
          r.className = r.className.replaceAll(_self.selectedClass,"");
         _selectedRegions.remove(r);
        }
     }
   }
 }
 RegionSelect.prototype.onEnd = function(){
  if(this.selectDiv){
    this.selectDiv.style.display = "none"; 
  }
  this.isSelect = false;
  //_selectedRegions = this.selectedRegion;
 }
 // 判断一个区域是否在选择区内
 RegionSelect.prototype.innerRegion = function(selDiv, region){
   var s_top = parseInt(selDiv.style.top);
   var s_left = parseInt(selDiv.style.left);
   var s_right = s_left + parseInt(selDiv.offsetWidth);
   var s_bottom = s_top + parseInt(selDiv.offsetHeight);
   var r_top = parseInt(region.offsetTop);
   var r_left = parseInt(region.offsetLeft);
   var r_right = r_left + parseInt(region.offsetWidth);
   var r_bottom = r_top + parseInt(region.offsetHeight);
    var t = Math.max(s_top, r_top);
     var r = Math.min(s_right, r_right);
     var b = Math.min(s_bottom, r_bottom);
     var l = Math.max(s_left, r_left);
      if (b > t+5  &&  r > l+5) {
          return region;
      } else {
          return null;
      }
 }
 RegionSelect.prototype.clearSelections = function(regions){
  for(var i=0; i<regions.length;i++){
   regions[i].className = regions[i].className.replaceAll(this.selectedClass,"");
  }
 }
 function getSelectedRegions(){
  return  _selectedRegions;
 }
 function showSelDiv(){
   var selInfo = "";
   var arr = getSelectedRegions();
   for(var i=0; i<arr.length;i++){
       selInfo += arr[i].innerHTML+"\n";
   }
   alert("共选择 "+arr.length+" 个文件,分别是:\n"+selInfo);
 }
// ]]></script>
<p><button onclick="showSelDiv();">getRegions</button></p>
<div class="fileDiv">file1</div>
<div class="fileDiv">file2</div>
<div class="fileDiv">file3</div>
<div class="fileDiv">file4</div>
<div class="fileDiv">file5</div>
<div class="fileDiv">file6</div>
<div class="fileDiv">file7</div>
<div class="fileDiv">file8</div>
<div style="float: left; width: 100%;"><button onclick="showSelDiv();">getRegions</button></div>
<script type="text/javascript">// <![CDATA[
new RegionSelect({
     region:'div.fileDiv',
     selectedClass: 'seled'
    }).select();
// ]]></script>
Javascript 相关文章推荐
PPK 谈 JavaScript 的 this 关键字 [翻译]
Sep 29 Javascript
javascript动态添加样式(行内式/嵌入式/外链式等规则)
Jun 24 Javascript
node.js中的console.error方法使用说明
Dec 10 Javascript
Jquery 实现checkbox全选方法
Jan 28 Javascript
AngularJS单选框及多选框实现双向动态绑定
Jan 13 Javascript
JavaScript和jQuery制作光棒效果
Feb 24 Javascript
详解Vue爬坑之vuex初识
Jun 14 Javascript
vue 2.x 中axios 封装的get 和post方法
Feb 28 Javascript
《javascript少儿编程》location术语总结
May 27 Javascript
vue实现图片上传预览功能
Dec 23 Javascript
jQuery实现开关灯效果
Aug 02 jQuery
如何利用JavaScript编写更好的条件语句详解
Aug 10 Javascript
用JS在浏览器中创建下载文件
Mar 05 #Javascript
使用iframe window的scroll方法控制iframe页面滚动
Mar 05 #Javascript
js写的方法实现上传图片之后查看大图
Mar 05 #Javascript
js数值和和字符串进行转换时可以对不同进制进行操作
Mar 05 #Javascript
JSON中双引号的轮回使用过程中一定要小心
Mar 05 #Javascript
关于jQuery中的each方法(jQuery到底干了什么)
Mar 05 #Javascript
JavaScript 实现简单的倒计时弹窗DEMO附图
Mar 05 #Javascript
You might like
用PHP和ACCESS写聊天室(四)
2006/10/09 PHP
PHPMailer安装方法及简单实例
2008/11/25 PHP
PHP可逆加密/解密函数分享
2012/09/25 PHP
php 实现Hash表功能实例详解
2016/11/29 PHP
一段多浏览器的&quot;复制到剪贴板&quot;javascript代码
2007/03/27 Javascript
一个可以随意添加多个序列的tag函数
2009/07/21 Javascript
json 入门基础教程 推荐
2009/10/31 Javascript
javascript下数值型比较难点说明
2010/06/07 Javascript
jQuery autocomplate 自扩展插件、自动完成示例代码
2011/03/28 Javascript
jquery的flexigrid无法显示数据提示获取到数据
2013/07/19 Javascript
js统计录入文本框中字符的个数并加以限制不超过多少
2014/05/23 Javascript
jQuery源码解读之addClass()方法分析
2015/02/20 Javascript
使用jquery提交form表单并自定义action的方法
2016/05/25 Javascript
javascript操作cookie
2017/01/17 Javascript
常用jQuery选择器汇总
2017/02/02 Javascript
如何使用JS在HTML中自定义字符串格式化
2017/07/20 Javascript
全面解析vue router 基本使用(动态路由,嵌套路由)
2018/09/02 Javascript
vue eslint简要配置教程详解
2019/07/26 Javascript
JS/jQuery实现超简单的Table表格添加,删除行功能示例
2019/07/31 jQuery
解决Layui中templet中a的onclick参数传递的问题
2019/09/20 Javascript
Python中序列的修改、散列与切片详解
2017/08/27 Python
python 遍历目录(包括子目录)下所有文件的实例
2018/07/11 Python
基于python SMTP实现自动发送邮件教程解析
2020/06/02 Python
CSS3实现复选框动画特效示例代码
2016/09/27 HTML / CSS
HTML5 Canvas渐进填充与透明实现图像的Mask效果
2013/07/11 HTML / CSS
加拿大休闲和工业服装和鞋类零售商:L’Équipeur
2018/01/12 全球购物
受希腊女神灵感的晚礼服、鸡尾酒礼服和婚纱:THEIA
2018/04/15 全球购物
Reformation官网:美国女装品牌
2018/09/14 全球购物
餐厅楼面主管岗位职责范本
2014/02/16 职场文书
个人课题方案
2014/05/08 职场文书
计算机网络专业自荐书
2014/06/09 职场文书
课外活动实习计划
2015/01/19 职场文书
培训督导岗位职责
2015/04/10 职场文书
《圆的周长》教学反思
2016/02/17 职场文书
PyQt5结合QtDesigner实现文本框读写操作
2021/06/11 Python
mysql如何配置白名单访问
2021/06/30 MySQL