首頁  >  文章  >  web前端  >  js實現帶框的拖曳效果

js實現帶框的拖曳效果

小云云
小云云原創
2018-03-26 16:55:311325瀏覽

本文主要和大家分享js實現帶框的拖曳效果,主要以程式碼的形式和大家分享,希望能幫助大家。

<!doctype html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
  <style>
  #box {
  width:100px;
  height:100px;
  background:#ff0099;
  position:absolute;
  
  }
  .box1 {
  border:1px solid #000000;
  position:absolute;
  
  }
  </style>
 </head>
 <body>
 <p id = &#39;box&#39;></p>
 <script>
 var box = document.getElementById(&#39;box&#39;);
     box.onmousedown = function(e){
  var box1 = document.createElement("p");
    document.body.appendChild(box1);
    box1.style.width = box.offsetWidth + &#39;px&#39;;
    box1.style.height = box.offsetHeight + &#39;px&#39;;
 box1.style.left = box.offsetLeft + &#39;px&#39;;
 box1.style.top = box.offsetTop + &#39;px&#39;;
    box1.className = &#39;box1&#39;;
    e = e || event;
 //计算鼠标在盒子中的位置;
 var x = e.pageX - box.offsetLeft;
 var y = e.pageY - box.offsetTop;
 document.onmousemove = function(e){


  e = e || event;
  //计算盒子在页面上的坐标;
  var xx = e.pageX - x;
  var yy = e.pageY - y;
  box1.style.left = xx + &#39;px&#39;;
  box1.style.top = yy + &#39;px&#39;;
 document.onmouseup = function(){
 box.style.left = box1.offsetLeft + &#39;px&#39;;
 box.style.top = box1.offsetTop + &#39;px&#39;;
 document.body.removeChild(box1);
 document.onmousemove = &#39;null&#39;;
 
 
 
 }
 
 return false;
 }
 
 
 }
 
 
 </script>
 </body>
</html>

以上是js實現帶框的拖曳效果的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn