簡體   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