添加具有其他坐标的div

问题描述 投票:0回答:2

我想通过输入文本字段给定的坐标将div放在另一个中。添加的跨度应与父坐标的相对位置成正比。问题在于它不添加任何内容,但是会更改画布的位置。

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

任何想法怎么了?

javascript html html5-canvas position
2个回答
1
投票

您的代码中有一些“ bug”,包括html和JS。

这里是一个有效的示例:http://jsfiddle.net/kGd2G/1/

即。使用div代替canvas

<div id="rectangle" style="width: 300px; height: 300px;"></div>

为了简化JS,我使用了一个“ template div”为要添加的矩形设置一些默认值。


4
投票

您可能应该使用.append()而不是.append().add()不会将div添加到DOM,而是将元素添加到一组匹配的元素。

Edit:经过深思熟虑,我看到您正在尝试将div附加到canvas元素。您可能会对检查.add()的位置感兴趣:

canvas元素的内容(如果有)是该元素的后备内容。

因此您可能应该用div替换canvas元素。或编辑您的问题以更好地反映此细节。

© www.soinside.com 2019 - 2024. All rights reserved.