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

javascript - Move at an angle, jquery, animate()? - Stack Overflow

programmeradmin3浏览0评论

is there a way to specify the angle when using

$(this).animate({'left': '+=30px'}, 1000);

I would like

$(this).animate({'48': '+=30px'}, 1000);

the 48 would be the angle

is there a way to specify the angle when using

$(this).animate({'left': '+=30px'}, 1000);

I would like

$(this).animate({'48': '+=30px'}, 1000);

the 48 would be the angle

Share Improve this question asked Jan 16, 2012 at 20:55 thelostthelost 7053 gold badges12 silver badges30 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

You can specify both left and top property:

$(this).animate({left: '+=30px', top: '+=30px'}, 1000);

In this case, the angle would be 45°.

To specify a different angle, first calculate cos(α) and sin(α). The cosinus specifies how far you have to go right, and the sinus how far to go up, to make a distance of 1 pixel in the specified angle. If you want to cover 30 pixels distance instead, multiply the sinus and cosinus results by 30.

I just wanted to correct a mistake in 32bitkid's otherwise excellent example from the best answer by Yogu.

If Math.PI is divded by -180 (instead of 180) it will result in the correct position for the div. 90 degree angle was moving div down instead of up.

$(function() {
    var dist = 30;
    var angle = 90;
    var x = Math.cos(angle*Math.PI/-180) * dist;
    var y = Math.sin(angle*Math.PI/-180) * dist;
    $("div").animate({'left': '+='+x+'px', 'top': '+='+y+'px'}, 1000);      
})

Here's the updated fiddle: http://jsfiddle/9yL8hxnz/

发布评论

评论列表(0)

  1. 暂无评论