现在的位置: 首页 > 综合 > 正文

用js打造类windows的虚线拖拽框

2018年03月29日 ⁄ 综合 ⁄ 共 2013字 ⁄ 字号 评论关闭

没事无聊,突然发现在windows下面一个很平常的细节,而在ie上没有,现在ria大行其道,很多web应用都在积极的效仿类windows的桌面效果,ext.dojo等等js类库中间都有很多绚丽的widget,很多人都认为js是一门玩具语言,很大一部分原因是他的

语言的自由,不同的程序员能写出不同的风格,还有就是js没有属于自己的图形类库(canvas至少没有普及和成熟),要画图,我们需要采用adobe的flash以及sun applet等等,不过,在浏览器,依旧,js的地位不可替代;

 

本来就是一个小小的demo,没多少价值含量,js也不是我的专长,不过要写好js,个人认为不是实现多少特效,而是要充分考虑到性能和机制,闭包,new function的时候做个什么,this是什么,js的对象是什么,类是什么,都值得我们研究,废话不说,小小的demo给出,希望能帮到初学者;

 

windows下面的效果:

我们可以用鼠标拖拽出一个半透明的淡蓝色框框,大小随鼠标移动;

 

用js实现,代码如下:

  1. <html>
  2.  <head>
  3.    <title>
  4.     dashedBox
  5.    </title>
  6.  </head>
  7.  <script language="javascript">
  8.  <!--
  9.   var beginX;
  10.   var beginY;
  11.   var drawable;
  12.   function beforeDrawDashedBox(){
  13.     drawable=true;
  14.     beginX=event.clientX;
  15.     beginY=event.clientY;
  16.     //alert("before");
  17.   }
  18.   function getDashedBox(){
  19.    var dashedBox=document.getElementById("dashedBox");
  20.    return dashedBox;
  21.   }
  22.   function clearDashedBox(){
  23.    if(getDashedBox()!=null){
  24.     document.body.removeChild(getDashedBox());
  25.    }
  26.   }
  27.   function drawBox(top,right,buttom,left){
  28.    var relLeft=left<right?left:right;
  29.    var relTop=top<buttom?top:buttom;
  30.    var relWidth=Math.abs(right-left);
  31.    var relHeight=Math.abs(buttom-top);
  32.    
  33.    var divEl=document.createElement("div");
  34.    divEl.id="dashedBox";
  35.    divEl.style.position="absolute";
  36.    divEl.style.border="1px BLUE dashed";
  37.    divEl.style.left=relLeft;
  38.    divEl.style.backgroundColor="blue";
  39.    divEl.style.filter="alpha(opacity=10)";
  40.    divEl.style.top=relTop;
  41.    divEl.style.width=relWidth;
  42.    divEl.style.height=relHeight;
  43.    document.body.appendChild(divEl);
  44.   }
  45.   function inDrawDashedBox(){
  46.     if(drawable==true){
  47.      clearDashedBox();
  48.      drawBox(beginY,beginX,event.clientY,event.clientX);
  49.     // alert("in");
  50.     }
  51.   }
  52.   function afterDrawDashedBox(){
  53.    drawable=false;
  54.    clearDashedBox();
  55.   // alert("after");
  56.   }
  57.   function loadDashdBoxFn (){
  58.    document.onmousedown=beforeDrawDashedBox;
  59.    document.onmousemove=inDrawDashedBox;
  60.    document.onmouseup=afterDrawDashedBox;
  61.   }
  62.   window.onload=loadDashdBoxFn;
  63.   </script>
  64.   <body>
  65.   </body>
  66.   </html>

 

ie浏览器下效果如图:

很遗憾,因为随手写的,暂时只支持ie,firefox下面不支持,跨浏览器是js的痛啊!

 

【上篇】
【下篇】

抱歉!评论已关闭.