javascript 旋转 div 如何设置围绕哪个点旋转?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15204815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rotating a div how to set around which point to rotate?
提问by Ivanka Todorova
My javascript is:
我的 javascript 是:
$(function() {
var $elie = $(".circle");
rotate(0);
function rotate(degree) {
$elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
$elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
timer = setTimeout(function() {
rotate(++degree);
},5);
}
});
How do I rotate the div around another center point?
如何围绕另一个中心点旋转 div?
Here's demo:
这是演示:
$(function() {
var $elie = $(".circle");
rotate(0);
function rotate(degree) {
$elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
$elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
timer = setTimeout(function() {
rotate(++degree);
},5);
}
});
.circle {
width: 200px;
height: 200px;
background: green;
border-radius: 50%;
border: 4px dashed black;
margin: calc(50vh - 100px) auto 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="circle">
</div>
回答by adeneo
You'd use transform-origin
for that :
你会使用transform-origin
:
$elie.css("-webkit-transform-origin", "50% 100%" );
or
或者
transform-origin: 100% 40%;
-ms-transform-origin: 100% 40%; /* IE 9 */
-webkit-transform-origin: 100% 40%; /* Safari and Chrome */
-moz-transform-origin: 100% 40%; /* Firefox */
-o-transform-origin: 100% 40%; /* Opera */
EDIT:
编辑:
To rotate around the center of the .circle
element, it first needs a height, otherwise there is no center. Then you could use percentages, or the much handier center
property, like so:
要绕.circle
元素的中心旋转,它首先需要一个高度,否则就没有中心。然后你可以使用百分比,或者更方便的center
属性,如下所示:
transform-origin:center center;