最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

css - How can I add an element with absolute position via jQuery or Javascript? - Stack Overflow

programmeradmin1浏览0评论

I have this line to add a new element in the screen, but the absolute position is not working.

Javascript

function drawElement(e,name){   
    $("#canvas").append("<div id='" + name + "' class='element'"
    + "left="+e.pageX+" top=" + e.pageY +">"
    + name
    +"</div>");
}

CSS

.element{
    display:inline-block;
    background:blue;
    position:absolute;  
}

What I doing wrong?

  1. List item

I have this line to add a new element in the screen, but the absolute position is not working.

Javascript

function drawElement(e,name){   
    $("#canvas").append("<div id='" + name + "' class='element'"
    + "left="+e.pageX+" top=" + e.pageY +">"
    + name
    +"</div>");
}

CSS

.element{
    display:inline-block;
    background:blue;
    position:absolute;  
}

What I doing wrong?

  1. List item
Share Improve this question edited Oct 8, 2011 at 14:41 Renato Dinhani asked Oct 8, 2011 at 14:11 Renato DinhaniRenato Dinhani 36.8k58 gold badges140 silver badges202 bronze badges 1
  • Can you give an example of the output you get pared to the output you expect? A working example of the current behaviour would also help. – Jon Cram Commented Oct 8, 2011 at 14:15
Add a ment  | 

3 Answers 3

Reset to default 3
var element = $('<div />',{'name': name, 'class': element})
                          .css({ 'left': e.pageX, 'top': e.pageY })
                          .html(name);  
$("#canvas").append(element); 
    function drawElement(e,name){   
        div = $("<div />")
            div.attr("id", name);
            div.attr("class", 'element')
            div.css("top", e.pageY)
            div.css("left", e.pageX)
            div.html(name)

            $("#canvas").append(div)
    }

Update: from ment below (didn't know you could do that!) :)

    function drawElement(e,name){   
        div = $("<div />")
        div.attr({id: name, class: 'element'});
        div.css({top: e.pageY, left: e.pageX})
        div.html(name)
                $("#canvas").append(div)
    }

Write the top and left positions into the style attribute, like this->

.append("<div id='" + name + "' class='element'"
+ "style='left:"+e.pageX+";top:" + e.pageY +";'>"

Although you should probably do it like this, so that it's more... controllable.

var newElem = $('<div />').addClass('element').css({'left': e.pageX, 'top' : e.pageY});

 $("#canvas").append(newElem);
发布评论

评论列表(0)

  1. 暂无评论