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

javascript - animate element dynamically on creation - Stack Overflow

programmeradmin0浏览0评论

I want to dynamically create divs, append them to the body and set a jQuery animation.

This is where the elements are created:

function drawSpot()
{
 var myH1 = document.createElement("div");
 myH1.style.position = "absolute";
 myH1.style.top = GetRandom(0,100)+"%";
 myH1.style.left = GetRandom(0,100)+"%";
 myH1.style.width="40px";
 myH1.style.height="40px";
 $("body").append(myH1);

}

And from the time on they are appended to the body, I want to start the animation.

I want to dynamically create divs, append them to the body and set a jQuery animation.

This is where the elements are created:

function drawSpot()
{
 var myH1 = document.createElement("div");
 myH1.style.position = "absolute";
 myH1.style.top = GetRandom(0,100)+"%";
 myH1.style.left = GetRandom(0,100)+"%";
 myH1.style.width="40px";
 myH1.style.height="40px";
 $("body").append(myH1);

}

And from the time on they are appended to the body, I want to start the animation.

Share Improve this question edited Jul 21, 2011 at 12:12 dilbert asked Jul 21, 2011 at 12:10 dilbertdilbert 1271 silver badge8 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 7

If you already using jQuery, you should do it all the way:

$('<div>', {
    css: {
        position:   'absolute',
        top:        GetRandom(0,100)+'%',
        left:       GetRandom(0,100)+'%',
        width:      '40px',
        height:     '40px'
    }
}).appendTo( document.body ).animate({
    left:  '100%'  // for instance
}, 2000);

By using .appendTo() you still have a reference to your original object and be able to chain methods on it.

Ref.: jQuery constructor, .appendTo(), .animate()

demo: http://jsfiddle/dkuVu/

Use jQuery for creation of elements, and animate it when appending:

function drawSpot() {
 var myH1 = $("<div>").css({ position: "absolute",
                             top:      GetRandom(0,100)+"%",
                             left:     GetRandom(0,100)+"%",
                             width:    40,
                             height:   40 });
 $("body").append(myH1.animate(...));
}

http://jsfiddle/nagCf/

That should work

function drawSpot()
{
   var myH1 = '<div id="newDiv">Some Text</div>';
   $("body").append(myH1);

   $("#newDiv").css({'position' : 'absolute',
                     'top' : GetRandom(0,100)+"%",
                     'left' :GetRandom(0,100)+"%",
                     'width':'40px',
                     'height':'40px' 
                   });

   $("#newDiv").hide().fadeIn(500);
}

You can use : $(myH1).animate({left:'*randomvalue*', top:'*randomvalue*'},1000); after the append.

http://jsfiddle/Wumrr/2/

发布评论

评论列表(0)

  1. 暂无评论