Positioning divs in a circle using JavaScript

后端 未结 4 441
深忆病人
深忆病人 2020-11-29 00:22

I am trying to position 15 div elements evenly in a circle with a radius of 150px. I\'m using the following code, which seems to give an oddly ecce

4条回答
  •  一生所求
    2020-11-29 00:36

    Yet another solution, based on ideas from other solutions I've seen

    http://jsfiddle.net/0hr1n7a2/6/

    (function() {
      var radians, radius;
    
      radius = 150;
        
      var totalItems = 48
      var item = 0;
      function positionTarget() 
      {
        var x, y, angle = 0, step = (2*Math.PI) / totalItems;
        var width = $('#container').width()/2;
        var height = $('#container').height()/2;
        var itemW = 20, itemH = 2;
        var deg = 0;    
     while(item <= totalItems)
     {        
      x = Math.round(width + radius * Math.cos(angle) - itemW/2);
      y = Math.round(height + radius * Math.sin(angle) - itemH/2);        
            //console.log(x + "," + y);
         
      $('#container').append('
    ') $('div#'+item).css('position', 'absolute') .css('width', itemW+'px').css('height', itemH+'px') .css('left', x+'px').css('top', y+'px') .css('background-color', 'blue') .css('transform-origin', x+'px' -y+'px') .css('transform', 'rotate('+ deg +'deg)') .css('border', 'solid 1px #000'); angle += step; ++item; deg += 360/totalItems; //console.log(deg) } } $('#theButton').on('click', function() { positionTarget(); }) })();
    #container { width: 600px; height: 600px; border: 1px solid #000; position: relative; }
    
        
    

提交回复
热议问题