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

代码如下:

<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>

(0)

相关推荐

  • Javascript实现的类似Google的Div拖动效果代码

    复制代码 代码如下: JScript 文件: //检测浏览器 MSIE Firefox var ie=false,moz=false; (function() {//check the browser var userAgent=navigator.userAgent; if(userAgent.indexOf("MSIE")!=-1) ie=true; else if(userAgent.indexOf("Firefox")!=-1) moz=true; })()

  • 纯js实现的积木(div层)拖动功能示例

    本文实例讲述了纯js实现的积木(div层)拖动功能.分享给大家供大家参考,具体如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>拖动</title> <style type="text/css"> </style> </head> <bo

  • javascript div 弹出可拖动窗口

    /* * 创建弹出div窗口. 1.接口说明:DivWindow(id,title,width,height,content) 构造函数,创建一个弹出窗口对象 参数:id 弹出窗口id: title:弹出窗口标题名称: width:弹出窗口宽度 height:弹出窗口高度 content: 弹出窗口显示内容 2.接口说明: closeDivWindow(id) 关闭窗口 参数: id 弹出窗口id 3.接口说明:setPopupTopTitleFontColor(PopupTopTitleFon

  • js 可拖动列表实现代码

    补充一点: 要禁止移动中选中文字,FF可以设置CSS xxxx{-moz-user-select:none;} 其他的浏览器可以设置 XXXX.onselectstart = function(){return false} 一种实现原理就是点击没目标元素之后,创建一个占位元素(或者复制一份目标元素,即拷贝B),然后拖动目标元素(或者复制的来的新元素B): 找到相应的位置之后,插入目标元素.清除占位元素或者B. 比如有一个列表: 复制代码 代码如下: <!DOCTYPE html PUBLIC

  • javascript 事件处理、鼠标拖动效果实现方法详解

    先看看要拖动的层(模拟窗口)的效果图吧. 要实现的拖动效果:鼠标左键在窗口上方的标题栏上按下,同时移动鼠标,窗口跟着移动.窗口: 复制代码 代码如下: <div id="win"> <div id="win_header"></div> </div> 一点准备工作: 要让窗口能自由移动,那么窗口的定位(position)应该采用绝对定位(absolute): 给窗口添加标题栏,这里使用一个放在窗口顶部的层实现,同时将标

  • angularjs创建弹出框实现拖动效果

    本文实例介绍了angularjs创建弹出框实现拖动效果的相关代码,项目中需要将angular-ui-bootstrap中用到的弹出框,使之可拖动,分享给大家供大家参考,具体内容如下 运行效果图: 由于源文件中没有实现,需要自己实现指令,以下即为该指令,亲测可以实现. .directive('draggable', ['$document', function($document) { return function(scope, element, attr) { var startX = 0,

  • js通过八个点 拖动改变div大小的实现方法

    复制代码 代码如下: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Resize</title> <style type="text/css"> #rRightDown,#rLeftDown,#rLeftUp,#rRightUp,#rRigh

  • js实现可拖动DIV的方法

    随着时代的变化,越来越感觉到js的重要性,js不仅可以做web页面(如Ext框架),还可以做一些web的特效,这些特效不仅兼容PC,而且兼容手机端,毕竟是基于浏览器的,和平台没关系.现在微软的windows8 系统的App都可以用js开发了,大家有时间可以去尝试一下. 现在切入正题,说一下js 实现可拖动Div.实现这个功能我们先说一下思路: 1.捕捉鼠标div的mousedown事件 2.捕捉 document的   mousemove事件 3.取消事件 然后我们看一下代码: 复制代码 代码如

  • JS实现可缩放、拖动、关闭和最小化的浮动窗口完整实例

    本文实例讲述了JS实现可缩放.拖动.关闭和最小化的浮动窗口方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999

  • javascript之可拖动的iframe效果代码

    // HISTORY// ------------------------------------------------------------------// Jan 23, 2004: Fixed problems which caused the script not to work in//               some framed situations. Improved browser support.//               Added easier "addH

  • html+javascript实现可拖动可提交的弹出层对话框效果

    复制代码 代码如下: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>JAVASCRI

  • JS高级拖动技术 setCapture,releaseCapture

    复制代码 代码如下: <script type="text/javascript"> <!-- window.onload=function(){ objDiv = document.getElementById('drag'); drag(objDiv); }; function drag(dv){ dv.onmousedown=function(e){ var d=document; e = e || window.event; var x= e.layerX |

随机推荐