JavaScript simple to implement mouse drag selection function

Source: Internet
Author: User
Tags abs cdata continue min split tagname

  This article is mainly on the JavaScript simple implementation of mouse drag selection function sample code is introduced, the need for friends can come to the reference, I hope to help you.

The code is as follows: <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 (it EM = = This[i])     break;  }   if (i = = this.length)    return;   for (var j = i; J < This.length-1; J +) {   this[j] = this[j + 1];  }   This.lengt h--;  }    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 n EW 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 (' # ');       VA R 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 = ' * ';      }     &NBSP ;   var found = new Array;       var foundcount = 0;       for (var h = 0; h < currentcontext.length; h++) {        VAR elements;         if (tagName = = ' * ') {            elements = Getallchildren (Currentcon TEXT[H]);        } else {            elements = Currentcontext[h].getelementsbyt Agname (TagName);        }         for (var j = 0; J < Elements.length; J +) {    &NB Sp     found[foundcount++] = elements[j];        }       {      currentcontext = new Array;       var currentcontextindex = 0;      for (var k = 0; k < found.length k++) {        if (Found[k].classname  &&A mp  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;       V Ar attroperator = regexp.$3;       var attrValue = regexp.$4;       if (!tagname) {        tagName = ' * ';      }     &NBSP ; var found = new Array;       var foundcount = 0;       for (var h = 0; h < currentcontext.length; h++) {        VAR elements;         if (tagName = = ' * ') {&nbsP           elements = Getallchildren (Currentcontext[h]);        } else {            elements = Currentcontext[h].getelementsbyt Agname (TagName);        }         for (var j = 0; J < Elements.length; J +) {    &NB Sp     found[foundcount++] = elements[j];        }       {      currentcontext = new Array;       var currentcontextindex = 0;       var checkfunction;        switch (attroperator) {        CAS E ' = ':           checkfunction = function (e) {return (E.getattribute (attrname) = = AttrValue);} ;           break;         case ' ~ ':          checkfunction = function (e) {return (e.get Attribute (attrname). Match (new RegExp (' B ' +Attrvalue+ ' B ')); };           break;         case ' | ':    ,       checkfunction = function (e) {return (E.getattrib Ute (Attrname). Match (new RegExp (' ^ ' +attrvalue+ '-? ')); };           break;         case ' ^ ':    ,       checkfunction = function (e) {return (E.getattrib Ute (Attrname). IndexOf (attrValue) = = 0); };           break;         case "$ ':            checkfunction = function (e) {return (e.get Attribute (attrname). LastIndexOf (attrValue) = = E.getattribute (attrname). Length-attrvalue.length); };           break;         case ' * ':            checkfunction = function (e) {return (e.get Attribute (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];        } &nbsp ;    }       continue;    }     TagName = token;     var found = new Array;     var foundcount = 0;     for (var h = 0; h < currentcontext.length h++) {      var elements = currentcontext[h].g Etelementsbytagname (TagName);       for (var j = 0; J < Elements.length; J +) {        found[foundcount++] = Elem ENTS[J];      }    }     CurrentContext = found  }   return currentcontext; }    function addevent (eventtype,eventfunc,eventobj) {    EVENTOBJ = EVENTOBJ | | document;   &NBS P 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) EV T.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;     &NB Sp;for (var i=0 i< _regions.length;i++) {       _regions[i].onmousedown = function () {  &NBSP ;      var evt = window.event | | Arguments[0];          if (!evt.shiftkey  &&  !evt.ctrlkey) {        &NBS P Clear all Select styles           _self.clearselections (_regions);           This.classname = "" +_self.selectedclass;          //Empty selected array and add the elements of the current 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.replac Eall (_self.selectedclass, "");             _selectedregions.remove (this);           {        &NBSP,          CLEAREVENTBUBBL E (EVT);       &NBSP}        this.regions.push (_regions[i]);     &NBSP}   &nbsp}    this.selectedclass = selregionprop["Selectedclass"];    this.selectedregion = [];    THIS.SELECTDIV = null;    THIS.STARTX = null;    this.starty = null;  } &nbsp  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.O Nselect (EVT);     cleareventbubble (EVT);  },document);     addevent ("MouseUp", function () {    _self.onend ();  },document); &NBSP}    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;   &NBSP}    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 = _se Lf.innerregion (_SELF.SELECTDIV,R);        if (SR  &&  r.classname.indexof (_self.selectedclass) = = 1) {    & nbsp     R.classname = R.classname + "" +_self.selectedclass;            _selectedregio Ns.push (R);        }else if (!sr  &&  r.classname.indexof (_self.selectedclass)!=-1) {  & nbsp       R.classname = R.classname.replaceall (_self.selectedclass, "");          _selectedregions.remove (R);        }         { } &nbsp}    regionselect.prototype.onen D = function () {  if (this.selectdiv) {    THIS.SELECTDIV.STyle.display = "None";   }   This.isselect = false;  //_selectedregions = this.selectedregion; &NBSP}    //Determines whether a zone is in the selection  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;      }   &NBSP}    regionselect.prototype.clearselections = function (regions) {  for (var i=0; i<regions.length;i++) {   regions[i].classname = Regions[i].classname.replaceall (This.selectedclass, "")  }  }   & Nbsp;function getselectedregions () {  return  _selectedRegions;  }    function Showseldiv () {& nbsp  var selinfo = "";    var arr = getselectedregions ();    for (var i=0 i<arr.length;i++) {       selinfo + = arr[i].innerhtml+ "n";     }      alert ("+arr.length+" files, respectively: n "+selinfo);"   &NBSP}//]]></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 '   &N Bsp ). Select (); ]]></script>    
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.