programing

jquery.animate()가 있는 CSS 회전 교차 브라우저

subpage 2023. 9. 26. 22:22
반응형

jquery.animate()가 있는 CSS 회전 교차 브라우저

크로스 브라우저 호환 로테이션(즉, 9+)을 만드는 중이며 jsfiddle에 다음 코드가 있습니다.

$(document).ready(function () { 
    DoRotate(30);
    AnimateRotate(30);
});

function DoRotate(d) {

    $("#MyDiv1").css({
          '-moz-transform':'rotate('+d+'deg)',
          '-webkit-transform':'rotate('+d+'deg)',
          '-o-transform':'rotate('+d+'deg)',
          '-ms-transform':'rotate('+d+'deg)',
          'transform': 'rotate('+d+'deg)'
     });  
}

function AnimateRotate(d) {

        $("#MyDiv2").animate({
          '-moz-transform':'rotate('+d+'deg)',
          '-webkit-transform':'rotate('+d+'deg)',
          '-o-transform':'rotate('+d+'deg)',
          '-ms-transform':'rotate('+d+'deg)',
          'transform':'rotate('+d+'deg)'
     }, 1000); 
}

CSS와 HTML은 정말 간단하며 데모용입니다.

.SomeDiv{
    width:50px;
    height:50px;       
    margin:50px 50px;
    background-color: red;}

<div id="MyDiv1" class="SomeDiv">test</div>
<div id="MyDiv2" class="SomeDiv">test</div>

은 합니다를 할 때 합니다..css()사용할 때는 그렇지 않습니다..animate(); 왜 그런 것이고 고칠 방법이 있을까요?

감사해요.

CSS-변환은 아직 jQuery로 애니메이션화할 수 없습니다.다음과 같은 작업을 수행할 수 있습니다.

function AnimateRotate(angle) {
    // caching the object for performance reasons
    var $elem = $('#MyDiv2');

    // we use a pseudo object for the animation
    // (starts from `0` to `angle`), you can name it as you want
    $({deg: 0}).animate({deg: angle}, {
        duration: 2000,
        step: function(now) {
            // in the step-callback (that is fired each step of the animation),
            // you can use the `now` paramter which contains the current
            // animation-position (`0` up to `angle`)
            $elem.css({
                transform: 'rotate(' + now + 'deg)'
            });
        }
    });
}

스텝 콜백에 대한 자세한 내용은 http://api.jquery.com/animate/ #step을 참조하십시오.

http://jsfiddle.net/UB2XR/23/

그리고, 그건 그렇고: jQuery 1.7+로 css3 변환을 접두사 할 필요는 없습니다.

갱신하다

이것을 jQuery-plugin에 싸서 생활을 좀 더 편하게 할 수 있습니다.

$.fn.animateRotate = function(angle, duration, easing, complete) {
  return this.each(function() {
    var $elem = $(this);

    $({deg: 0}).animate({deg: angle}, {
      duration: duration,
      easing: easing,
      step: function(now) {
        $elem.css({
           transform: 'rotate(' + now + 'deg)'
         });
      },
      complete: complete || $.noop
    });
  });
};

$('#MyDiv2').animateRotate(90);

http://jsbin.com/ofagog/2/edit

업데이트2

는 을 조금 최적화했습니다.easing,duration그리고.complete

$.fn.animateRotate = function(angle, duration, easing, complete) {
  var args = $.speed(duration, easing, complete);
  var step = args.step;
  return this.each(function(i, e) {
    args.complete = $.proxy(args.complete, e);
    args.step = function(now) {
      $.style(e, 'transform', 'rotate(' + now + 'deg)');
      if (step) return step.apply(e, arguments);
    };

    $({deg: 0}).animate({deg: angle}, args);
  });
};

업데이트 2.1

문제를 지적해주신 마테오님께 감사드립니다.this- 은 한.. ..callback. 콜백을 다음과 같이 바인딩하여 수정하는 경우jQuery.proxy각 노드에서

이전에 업데이트 2부터 코드에 에디션을 추가했습니다.

업데이트 2.2

이것은 회전을 앞뒤로 전환하는 것과 같은 작업을 수행하려는 경우 가능한 수정 사항입니다.함수에 시작 매개 변수를 추가하고 이 줄을 교체했습니다.

$({deg: start}).animate({deg: angle}, args);

시작 정도를 설정하고 싶든 말든 모든 사용 사례에 대해 보다 일반적으로 만드는 방법을 아는 사람이 있다면 적절한 편집을 해주십시오.


용법...is quite simple!

원하는 결과에 도달할 수 있는 방법은 크게 두 가지입니다.그러나 우선, 그 논쟁을 살펴보도록 하겠습니다.

jQuery.fn.animateRotate(angle, duration, easing, complete)

을 선택 "angle" 로 .jQuery.fn.animate:

duration: 400
easing: "swing"
complete: function () {}

첫 번째

이 방법은 짧은 방법이지만, 우리가 논쟁을 더 많이 할 수록 좀 불분명해 보입니다.

$(node).animateRotate(90);
$(node).animateRotate(90, function () {});
$(node).animateRotate(90, 1337, 'linear', function () {});

두번째

인수가 3개 이상일 경우 개체를 사용하는 것을 선호하기 때문에 이 구문이 가장 좋습니다.

$(node).animateRotate(90, {
  duration: 1337,
  easing: 'linear',
  complete: function () {},
  step: function () {}
});

고마워 이카트!대단한 공헌.당신 플러그인을 좀 더 살폈어요.전체 제어 및 크로스 브라우저 CSS를 위해 startAngle을 추가했습니다.

$.fn.animateRotate = function(startAngle, endAngle, duration, easing, complete){
    return this.each(function(){
        var elem = $(this);

        $({deg: startAngle}).animate({deg: endAngle}, {
            duration: duration,
            easing: easing,
            step: function(now){
                elem.css({
                  '-moz-transform':'rotate('+now+'deg)',
                  '-webkit-transform':'rotate('+now+'deg)',
                  '-o-transform':'rotate('+now+'deg)',
                  '-ms-transform':'rotate('+now+'deg)',
                  'transform':'rotate('+now+'deg)'
                });
            },
            complete: complete || $.noop
        });
    });
};

jQuery를 통해 CSS3 애니메이션을 다루게 된다면 jQuery transit은 아마도 당신의 삶을 더 편하게 해줄 것입니다.

편집 2014년 3월 (게시한 이후로 계속해서 제 조언이 찬반투표를 받았기 때문에)

제가 처음에 위의 플러그인을 암시했던 이유를 설명하겠습니다.

업데이트 중DOM한 걸음 한 걸음에 (즉)$.animate)는 성능 측면에서 이상적이지 않습니다.그것은 작동하지만 아마도 순수한 CSS3 전환이나 CSS3 애니메이션보다 느릴 것입니다.

처음부터 끝까지 어떤 모습으로 전환될지 표시하면 브라우저가 미리 생각할 수 있는 기회를 얻기 때문입니다.

예를 들어 각 전환 상태에 대한 CSS 클래스를 만들고 jQuery를 사용하여 애니메이션 상태를 전환할 수 있습니다.

이것은 일반적으로 비즈니스 로직과 혼합하는 대신 CSS의 나머지 부분과 함께 애니메이션을 조정할 수 있기 때문에 매우 깔끔합니다.

// initial state
.eye {
   -webkit-transform: rotate(45deg);
   -moz-transform: rotate(45deg);
   transform: rotate(45deg);
   // etc.

   // transition settings
   -webkit-transition: -webkit-transform 1s linear 0.2s;
   -moz-transition: -moz-transform 1s linear 0.2s;
   transition: transform 1s linear 0.2s;
   // etc.
}

// open state    
.eye.open {

   transform: rotate(90deg);
}

// Javascript
$('.eye').on('click', function () { $(this).addClass('open'); });

변환 매개변수가 동적인 경우 스타일 특성을 대신 사용할 수도 있습니다.

$('.eye').on('click', function () { 
    $(this).css({ 
        -webkit-transition: '-webkit-transform 1s ease-in',
        -moz-transition: '-moz-transform 1s ease-in',
        // ...

        // note that jQuery will vendor prefix the transform property automatically
        transform: 'rotate(' + (Math.random()*45+45).toFixed(3) + 'deg)'
    }); 
});

MDN의 CSS3 전환에 대한 훨씬 더 자세한 정보.

하지만 그 외에도 몇 가지 주의해야 할 사항이 있는데 복잡한 애니메이션이나 체인 등이 있다면 이 모든 것이 다소 까다로워질 수 있습니다. jQuery Transit는 모든 까다로운 부분을 처리합니다.

$('.eye').transit({ rotate: '90deg'}); // easy huh ?

IE7+를 포함한 이 크로스 브라우저를 수행하려면 변환 매트릭스로 플러그인을 확장해야 합니다.벤더 프리픽스는 jquery-1.8+의 jQuery에서 행해지므로 저는 그것을 생략하겠습니다.transform소유물.

$.fn.animateRotate = function(endAngle, options, startAngle)
{
    return this.each(function()
    {
        var elem = $(this), rad, costheta, sintheta, matrixValues, noTransform = !('transform' in this.style || 'webkitTransform' in this.style || 'msTransform' in this.style || 'mozTransform' in this.style || 'oTransform' in this.style),
            anims = {}, animsEnd = {};
        if(typeof options !== 'object')
        {
            options = {};
        }
        else if(typeof options.extra === 'object')
        {
            anims = options.extra;
            animsEnd = options.extra;
        }
        anims.deg = startAngle;
        animsEnd.deg = endAngle;
        options.step = function(now, fx)
        {
            if(fx.prop === 'deg')
            {
                if(noTransform)
                {
                    rad = now * (Math.PI * 2 / 360);
                    costheta = Math.cos(rad);
                    sintheta = Math.sin(rad);
                    matrixValues = 'M11=' + costheta + ', M12=-'+ sintheta +', M21='+ sintheta +', M22='+ costheta;
                    $('body').append('Test ' + matrixValues + '<br />');
                    elem.css({
                        'filter': 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')',
                        '-ms-filter': 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')'
                    });
                }
                else
                {
                    elem.css({
                        //webkitTransform: 'rotate('+now+'deg)',
                        //mozTransform: 'rotate('+now+'deg)',
                        //msTransform: 'rotate('+now+'deg)',
                        //oTransform: 'rotate('+now+'deg)',
                        transform: 'rotate('+now+'deg)'
                    });
                }
            }
        };
        if(startAngle)
        {
            $(anims).animate(animsEnd, options);
        }
        else
        {
            elem.animate(animsEnd, options);
        }
    });
};

참고: 매개변수options그리고.startAngle설정만 하면 되는 경우 선택 사항입니다.startAngle사용하다{}아니면null위해서options.

사용 예시:

var obj = $(document.createElement('div'));
obj.on("click", function(){
    obj.stop().animateRotate(180, {
        duration: 250,
        complete: function()
        {
            obj.animateRotate(0, {
                duration: 250
            });
        }
    });
});
obj.text('Click me!');
obj.css({cursor: 'pointer', position: 'absolute'});
$('body').append(obj);

데모에 대해서는 이 jsfiddle도 참조하십시오.

업데이트: 이제 통과할 수도 있습니다.extra: {}선택사항들에그러면 다른 애니메이션을 동시에 실행할 수 있습니다.예를 들어,

obj.animateRotate(90, {extra: {marginLeft: '100px', opacity: 0.5}});

이렇게 하면 요소가 90도 회전하고, 100px로 오른쪽으로 이동하여 애니메이션이 진행되는 동안 동시에 반투명 상태가 됩니다.

이것이 제 해결책입니다.

var matrixRegex = /(?:matrix\(|\s*,\s*)([-+]?[0-9]*\.?[0-9]+(?:[e][-+]?[0-9]+)?)/gi;

var getMatches = function(string, regex) {
    regex || (regex = matrixRegex);
    var matches = [];
    var match;
    while (match = regex.exec(string)) {
        matches.push(match[1]);
    }
    return matches;
};

$.cssHooks['rotation'] = {
    get: function(elem) {
        var $elem = $(elem);
        var matrix = getMatches($elem.css('transform'));
        if (matrix.length != 6) {
            return 0;
        }
        return Math.atan2(parseFloat(matrix[1]), parseFloat(matrix[0])) * (180/Math.PI);
    }, 
    set: function(elem, val){
        var $elem = $(elem);
        var deg = parseFloat(val);
        if (!isNaN(deg)) {
            $elem.css({ transform: 'rotate(' + deg + 'deg)' });
        }
    }
};
$.cssNumber.rotation = true;
$.fx.step.rotation = function(fx) {
    $.cssHooks.rotation.set(fx.elem, fx.now + fx.unit);
};

그러면 기본 애니매이션 fkt에서 사용할 수 있습니다.

//rotate to 90 deg cw
$('selector').animate({ rotation: 90 });

//rotate to -90 deg ccw
$('selector').animate({ rotation: -90 });

//rotate 90 deg cw from current rotation
$('selector').animate({ rotation: '+=90' });

//rotate 90 deg ccw from current rotation
$('selector').animate({ rotation: '-=90' });

jQuery.transit이 jQuery.easing과 호환되지 않기 때문에 다른 답변입니다.이 솔루션은 jQuery 확장으로 제공됩니다.보다 일반적으로 회전은 특정한 경우입니다.

$.fn.extend({
    animateStep: function(options) {
        return this.each(function() {
            var elementOptions = $.extend({}, options, {step: options.step.bind($(this))});
            $({x: options.from}).animate({x: options.to}, elementOptions);
        });
    },
    rotate: function(value) {
        return this.css("transform", "rotate(" + value + "deg)");
    }
});

사용 방법은 다음과 같이 간단합니다.

$(element).animateStep({from: 0, to: 90, step: $.fn.rotate});

setInterval이 있는 플러그인 크로스 브라우저를 사용하지 않을 경우:

                        function rotatePic() {
                            jQuery({deg: 0}).animate(
                               {deg: 360},  
                               {duration: 3000, easing : 'linear', 
                                 step: function(now, fx){
                                   jQuery("#id").css({
                                      '-moz-transform':'rotate('+now+'deg)',
                                      '-webkit-transform':'rotate('+now+'deg)',
                                      '-o-transform':'rotate('+now+'deg)',
                                      '-ms-transform':'rotate('+now+'deg)',
                                      'transform':'rotate('+now+'deg)'
                                  });
                              }
                            });
                        }

                        var sec = 3;
                        rotatePic();
                        var timerInterval = setInterval(function() {
                            rotatePic();
                            sec+=3;
                            if (sec > 30) {
                                clearInterval(timerInterval);
                            }
                        }, 3000);

언급URL : https://stackoverflow.com/questions/15191058/css-rotation-cross-browser-with-jquery-animate

반응형