我想将一个 div 放入另一个 div 中,其坐标由输入文本字段给出。添加的跨度应该具有与父级坐标的相对位置。 问题是它没有添加任何东西,但它改变了 Canvas 的位置。
<html>
<head>
<style>
#rectangle { position: relative; }
</style>
<body>
300 x 300 px MAX<br/>
<canvas id="rectangle" width="300" height="300"></canvas>
<br/>
<table>
<tr>
<td>Horizontal starting cordinate:</td>
<td><input type="text" id = "x" value = ""/></td>
</tr>
<tr>
<td>Vertical starting cordinate:</td>
<td><input type="text" id = "y"/></td>
</tr>
<tr>
<td>Width of the rectangle:</td>
<td><input type="text" id = "width"/></td>
</tr>
<tr>
<td>Height of the rectangle:</td>
<td><input type="text" id = "height"/></td>
</tr>
<tr>
<td></td>
<td><input type="button" id = "draw" value = "Click"/></td>
</tr>
</table>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$("#draw").click(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var x1 = parseInt($("#x").val());
var y1 = parseInt($("#y").val());
var width = parseInt($("#width").val());
var height = parseInt($("#height").val());
$("#rectangle")
.add("div")
.css("id", "right-zone")
.css("z-index", "5")
.css("position", "absolute")
.css("left", x1)
.css("top", y2)
.css("width", width)
.css("height", height)
.css("background-color", "#FF0000")
.css("border", "solid red 1px");
});
})
</script>
有什么问题吗?
最佳答案
您可能应该使用.append()
而不是.add()
。 .add()
不会将 div 添加到 DOM,而是将一个元素添加到一组匹配的元素中。
编辑:再想一想,我发现您正在尝试将 div 附加到 canvas 元素。您可能有兴趣检查 this ,其中指出:
The contents of the canvas element, if any, are the element's fallback content.
所以你应该用 div 替换你的 canvas 元素。或者编辑您的问题以更好地反射(reflect)此细节。
关于javascript - 添加一个div,其坐标在另一个div中给出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15789277/