相对于父级创建和定位div

时间:2016-02-01 21:30:14

标签: javascript

我正在尝试在父div上创建(和定位)矩形div。创建的div应该相对定位。这是一个有用的 jsfiddle 示例 - >只需按住鼠标键即可绘制一些矩形。



var newRect = null;
 var offset = $('#page').offset();
 
function point(x, y) {
  this.x = x;
  this.y = y;
}
 
function rect(firstPoint) {
  this.firstPoint = firstPoint;
  this.div = document.createElement("div");
  this.div.style.position = "relative";
  this.div.style.border = "solid 1px grey";
  this.div.style.top = this.firstPoint.y+"px";
  this.div.style.left = this.firstPoint.x+"px";
  this.div.style.width = "0px";
  this.div.style.height = "0px";
  $("#page").append(this.div);
}


$("#page").mousedown(function (e) {
  if(e.which == 1) {
    var x = e.pageX - offset.left;
    var y = e.pageY - offset.top;
    newRect = new rect(new point(x, y));
  }
});
    
$("#page").mousemove(function (e) {
  if(newRect) {
    newRect.div.style.width = Math.abs(newRect.firstPoint.x-(e.pageX - offset.left))+"px";
    newRect.div.style.height = Math.abs(newRect.firstPoint.y-(e.pageY - offset.top))+"px";
  }
});
    
$("#page").mouseup(function (e) {
  if(e.which == 1 && newRect != null) {
    if(Math.abs(newRect.firstPoint.x-(e.pageX - offset.left)) < 10) {
      $("#"+newRect.div.id).remove();
      newRect = null;
      return;
    }

    $("#"+newRect.div.id).on('mousedown', function (e) {
      e.stopImmediatePropagation();
    });

    newRect = null;
  }
});
&#13;
#page{
    width: 210mm;
    height: 297mm;
    border:solid 2px #6D6D6D;
    cursor: crosshair;
    background-color: white;
    float:left;
    background-repeat: no-repeat;
    background-size: contain;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="page">
</div>
&#13;
&#13;
&#13;

绘制正确定位的第一个矩形后,每个矩形都定位为false。我认为这个位置的计算有问题......也许有人可以给我一个提示。

1 个答案:

答案 0 :(得分:3)

更改   this.div.style.position = "relative";

要  this.div.style.position = "absolute";

奖励:这是一个允许您向任何方向绘制的版本:https://jsfiddle.net/g4z7sf5c/5/

我只是将此代码添加到mousemove函数:

if (e.pageX < newRect.firstPoint.x) {
    newRect.div.style.left = e.pageX + "px";
}
if (e.pageY < newRect.firstPoint.y) {
    newRect.div.style.top = e.pageY + "px";
}