Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

javascript - Rotating a div how to set around which point to rotate?

My javascript is:

$(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?

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'd use transform-origin for that :

$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 */

FIDDLE


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:

transform-origin:center center;

DEMONSTRATION


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...