繁体   English   中英

相对于父级创建和定位div

[英]Create and position divs relative to parent

我试图在父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; } }); 
 #page{ width: 210mm; height: 297mm; border:solid 2px #6D6D6D; cursor: crosshair; background-color: white; float:left; background-repeat: no-repeat; background-size: contain; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="page"> </div> 

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

改变这个this.div.style.position = "relative";

to 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";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM