将DIV排列成圆圈并向外旋转它们

时间:2011-12-16 11:14:46

标签: javascript jquery

基本上我已经设法将我的DIV元素布局成圆形但我还没有设法弄清楚如何计算旋转角度需要让它们从圆心向外朝向。

$(document).ready(function(){
                var elems = document.getElementsByClassName('test_box');

                var increase = Math.PI * 2 / elems.length;
                var x = 0, y = 0, angle = 0;

                for (var i = 0; i < elems.length; i++) {
                    var elem = elems[i];
                    // modify to change the radius and position of a circle
                    x = 400 * Math.cos(angle) + 700;
                    y = 400 * Math.sin(angle) + 700;
                    elem.style.position = 'absolute';
                    elem.style.left = x + 'px';
                    elem.style.top = y + 'px';
                    //need to work this part out
                    var rot = 45;
                    elem.style['-moz-transform'] = "rotate("+rot+"deg)";
                    elem.style.MozTransform = "rotate("+rot+"deg)";
                    elem.style['-webkit-transform'] = "rotate("+rot+"deg)";
                    elem.style['-o-transform'] = "rotate("+rot+"deg)";
                    elem.style['-ms-transform'] = "rotate("+rot+"deg)";
                    angle += increase;
                    console.log(angle);
                }
            });

有没有人知道如何做到这一点。

干杯-C

2 个答案:

答案 0 :(得分:6)

请注意,rot取决于angle,但angle以弧度为单位。

DRY,所以要么从角度转换为腐烂:

// The -90 (degrees) makes the text face outwards.
var rot = angle * 180 / Math.PI - 90;

或者只是在设置样式时使用角度(但使用弧度作为单位),并删除rot的声明:

// The -0.5*Math.PI (radians) makes the text face outwards.
elem.style.MozTransform = "rotate("+(angle-0.5*Math.PI)+"rad)";

答案 1 :(得分:0)

试试这个:

 var rot = 90 + (i * (360 / elems.length));

http://jsfiddle.net/gWZdd/

演示

我在开始时添加了90度,以确保div的基线朝向中心,但您可以根据需要进行调整。