通过图像计数计算图像位置

时间:2016-04-04 09:57:11

标签: javascript jquery html css

周围有一个圆圈和一些物体。物体数量可能从 1到n (动态)不等。

如何自动将所有这些对象放在圆圈周围?

提前Tnx。

1 个答案:

答案 0 :(得分:2)

这是一种做法。我在代码中添加了注释来解释这些步骤。我冒昧地使用彩色div而不是图像,但效果是一样的。

// Editor to change the number of persons dynamically
var nr = document.getElementById('nr');
nr.addEventListener('keyup', function(){updatePersons();});

// The globe
var globe = document.getElementById('globe');

// A function to reinitialize the persons
function updatePersons() {
  var personCount = parseInt(nr.value);
  
  globe.innerHTML = ''; // A bit dirty way to remove all previous peeps
  
  // Just add them in a loop, and apply a transformation.
  for (var i = 0; i < personCount; i++) {
    var person = document.createElement('div');
    person.className = 'mens';
    var rotation = i * (360 / personCount);
    console.log(rotation);
    person.style.transform = 'translate(125px, -100px) rotate(' + rotation + 'deg)';
    globe.appendChild(person);
  }
}

// Initial positioning of persons.
updatePersons();
#nr {
  position: relative;
  z-index: 1;  
}

.corea {
  background-color: blue;
  border-radius: 50%;
  width: 300px;
  height: 300px;
  position: relative;
}

.mens {
  position: absolute; /* Needed, otherwise they influence each other */
  width: 50px;
  height: 100px;
  background-color: red;
  transform-origin: 25px 250px;
  
  /* Transform is set in Javascript */
  x-transform: translate(125px, -100px) rotate(180deg);
}
<input id="nr" value="5">
<div id="globe" class="corea">
</div>