我试图让div元素的网格围绕它的中心旋转。我用Google搜索并发现transform-origin属性可用于锚定旋转。但不知何故,它以一个角落作为锚旋转。我需要做些什么来使其工作并围绕网格的中心旋转?
var n = 20;
for( var i=0; i<n; ++i){
for(var j =0; j<n; ++j)
{
var div = document.createElement("div");
div.style.width = "9px";
div.style.height = "9px";
div.style.position = "absolute";
div.style.left = i*10 + "px";
div.style.top = j*10 + "px";
div.style.background = "black";
document.getElementById("top-div").appendChild(div);
}
}
var d = 0;
setInterval( function(e) {
d = (d + 1)%360;
document.getElementById("top-div").style.transform = "rotate("+ d + "deg)";
}, 1);
&#13;
#top-div{
transform-origin: center center;
-ms-transform-origin: center center;
-webkit-transform-origin: center center;
-moz-transform-origin: center center;
-o-transform-origin: center center;
}
&#13;
<div id='top-div'></div>
&#13;
使用谷歌浏览器版本57.0.2987.98(64位)
答案 0 :(得分:3)
问题是你没有为旋转div设置宽度和/或高度;它需要宽度和高度来计算锚点的位置。
var n = 20;
for (var i = 0; i < n; ++i) {
for (var j = 0; j < n; ++j) {
var div = document.createElement("div");
div.style.width = "9px";
div.style.height = "9px";
div.style.position = "absolute";
div.style.left = i * 10 + "px";
div.style.top = j * 10 + "px";
div.style.background = "black";
document.getElementById("top-div").appendChild(div);
}
}
var d = 0;
setInterval(function(e) {
d = (d + 1) % 360;
document.getElementById("top-div").style.transform = "rotate(" + d + "deg)";
}, 1);
&#13;
#top-div {
transform-origin: center center;
-ms-transform-origin: center center;
-webkit-transform-origin: center center;
-moz-transform-origin: center center;
-o-transform-origin: center center;
height: 200px;
width: 200px;
}
&#13;
<div id='top-div'></div>
&#13;