마우스 오버 후 마우스 아웃시 애니메이션을 반전하는 방법


91

따라서 마우스 아웃시 다음과 같은 리버스 애니메이션이 가능합니다.

.class{
   transform: rotate(0deg);

}
.class:hover{
   transform: rotate(360deg);
}

그러나 @keyframes 애니메이션을 사용할 때 작동하지 못했습니다. 예 :

.class{
   animation-name: out;
   animation-duration:2s;

}
.class:hover{
   animation-name: in;
   animation-duration:5s;
   animation-iteration-count:infinite;

}
@keyframe in{
    to {transform: rotate(360deg);}
}

@keyframe out{
    to {transform: rotate(0deg);}
}

반복과 애니메이션 자체가 필요하다는 것을 알고있는 최적의 솔루션은 무엇입니까?

http://jsfiddle.net/khalednabil/eWzBm/


여기 -jsfiddle.net/HQFby 와 같은 전환을 사용하는 것이 낫지 않습니까 ?
— piatek

대답은 이미 stackoverflow에 게시되었습니다. 여기에 링크 설명 입력
— watereffect

답변:


61

난 당신이이 있다면 생각 to, 당신은을 사용해야합니다 from. 나는 다음과 같은 것을 생각할 것입니다.

@keyframe in {
    from: transform: rotate(0deg);
    to: transform: rotate(360deg);
}

@keyframe out {
    from: transform: rotate(360deg);
    to: transform: rotate(0deg);
}

물론 이미 확인 했어야하지만 transformCSS3가 모든 곳에서 완전히 구현되지 않았기 때문에 속성 만 사용하는 것이 이상합니다 . 다음 사항을 고려하면 더 잘 작동 할 수 있습니다.

  • Chrome은을 사용 @-webkit-keyframes하며 특별한 버전이 필요하지 않습니다.
  • Safari는 @-webkit-keyframes버전 5 이상부터 사용합니다.
  • Firefox는 @keyframes버전 16부터 사용 (v5-15 사용 @-moz-keyframes)
  • Opera는 @-webkit-keyframes버전 15-22를 사용합니다 (v12 만 사용 @-o-keyframes).
  • Internet Explorer는 @keyframes버전 10 이상부터 사용합니다.

편집하다 :

나는 그 바이올린을 생각 해냈다.

http://jsfiddle.net/JjHNG/35/

최소한의 코드 사용. 당신이 기대했던 것에 접근하고 있습니까?


1
IE 10은 키 프레임 애니메이션을 지원합니다.
— dlev

4
그것은 전환을 되돌 리지만 문제는 마우스가 호버 전환이 끝나기 전에 나가면이 "점프"를 얻는다는 것입니다. 일부 검색 후에는 "animation-fill-mode : forwards;"에 대해 회전 끝 위치에서 되돌릴 수 있도록 요소의 상태가 "지속"되어야합니다. 사용할 수 있지만 작동하지 않는 것 같습니다.
— Khaled 2013 년

23
@Xaltar 앱을 처음로드하면 첫 번째 애니메이션이 사각형 위로 마우스를 가져 가지 않고 재생됩니다. 어쨌든 초기로드 애니메이션 발생을 중지 할 수 있습니까?
— jlewkovich

3
새로 고침 후 자체적으로 재생되는 첫 번째 애니메이션에 대한 해결책을 찾은 사람이 있습니까? 중요합니다.
— user2619824

2
처음 재생 애니메이션을 억제 할 수없는 경우이 대답은 궁극적으로 쓸모가
— NearHuscarl

21

이 모든 것보다 훨씬 쉽습니다. 요소에서 동일한 속성을 전환하기 만하면됩니다

.earth { width:  0.92%;    transition: width 1s;  }
.earth:hover { width: 50%; transition: width 1s;  }

https://codepen.io/lafland/pen/MoEaoG


4
예,하지만 속성이 하나만 변경된 경우에만 작동합니다.
— Marcus

4
@Marcustransition: border-color 0.3s, background-color 0.3s, color 0.3s;
— 돌진

4
D : 와우는, CSS는 좀 웹 프로그래밍했던 마지막 시간 이후 먼 길을왔다
— 프란츠 D.

5
애니메이션에 대한 질문입니다 !!
— iKamy

18

CSS 애니메이션만으로는 달성 할 수 없다고 생각합니다. (예를 들어) 두 애니메이션을 함께 연결하거나, 여러 중지, 반복을 사용하거나, 다른 방식으로 추가 파워 애니메이션이 부여하는 것을 활용하기를 원하기 때문에 CSS 전환 이 사용 사례를 충족 하지 않는다고 가정 합니다.

JavaScript를 사용하여 "over"및 "out"클래스를 연결하지 않고 마우스 아웃시 CSS 애니메이션을 트리거하는 방법을 찾지 못했습니다. : hover가 끝날 때 애니메이션을 트리거하는 기본 CSS 선언을 사용할 수 있지만 동일한 애니메이션이 페이지로드시 실행됩니다. "over"및 "out"클래스를 사용하여 정의를 기본 (로드) 선언과 두 개의 애니메이션 트리거 선언으로 분할 할 수 있습니다.

이 솔루션의 CSS는 다음과 같습니다.

.class {
    /* base element declaration */
}
.class.out {
   animation-name: out;
   animation-duration:2s;

}
.class.over {
   animation-name: in;
   animation-duration:5s;
   animation-iteration-count:infinite;
}
@keyframes in {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}
@keyframes out {
    from {
        transform: rotate(360deg);
    }
    to {
        transform: rotate(0deg);
    }
}

그리고 JavaScript (jQuery 구문)를 사용하여 클래스를 이벤트에 바인딩합니다.

$(".class").hover(
    function () {
        $(this).removeClass('out').addClass('over');
    },
    function () {
        $(this).removeClass('over').addClass('out');
    }
);

9

반전 된 애니메이션을 만드는 것은 간단한 문제에 대한 과잉입니다. 필요한 것은

animation-direction: reverse

그러나 이것은 애니메이션 사양이 너무 덤프되어 애니메이션을 다시 시작하는 방법을 추가하는 것을 잊었 기 때문에 자체적으로 작동하지 않습니다.

let item = document.querySelector('.item')

// play normal
item.addEventListener('mouseover', () => {
  item.classList.add('active')
})

// play in reverse
item.addEventListener('mouseout', () => {
  item.style.opacity = 0 // avoid showing the init style while switching the 'active' class

  item.classList.add('in-active')
  item.classList.remove('active')

  // force dom update
  setTimeout(() => {
    item.classList.add('active')
    item.style.opacity = ''
  }, 5)

  item.addEventListener('animationend', onanimationend)
})

function onanimationend() {
  item.classList.remove('active', 'in-active')
  item.removeEventListener('animationend', onanimationend)
}
@keyframes spin {
  0% {
    transform: rotateY(0deg);
  }
  100% {
    transform: rotateY(180deg);
  }
}

div {
  background: black;
  padding: 1rem;
  display: inline-block;
}

.item {
  /* because span cant be animated */
  display: block;
  color: yellow;
  font-size: 2rem;
}

.item.active {
  animation: spin 1s forwards;
  animation-timing-function: ease-in-out;
}

.item.in-active {
  animation-direction: reverse;
}
<div>
  <span class="item">ABC</span>
</div>



4

requestAnimationFrame을 사용하여 애니메이션을 재설정하고 브라우저가 다음 프레임에 그릴 때 되돌릴 수 있습니다.

또한 onmouseenter 및 onmouseout 이벤트 핸들러를 사용하여 애니메이션 방향을 반전합니다.

에 따라

이벤트 핸들러에 대기중인 모든 rAF는 동일한 프레임에서 실행됩니다. rAF에 대기중인 모든 rAF는 다음 프레임에서 실행됩니다.

function fn(el, isEnter) {
  el.className = "";
   requestAnimationFrame(() => {
    requestAnimationFrame(() => {
        el.className = isEnter? "in": "out";
    });
  });  
}
.in{
  animation: k 1s forwards;
}

.out{
  animation: k 1s forwards;
  animation-direction: reverse;
}

@keyframes k
{
from {transform: rotate(0deg);}
to   {transform: rotate(360deg);}
}
<div style="width:100px; height:100px; background-color:red" 
  onmouseenter="fn(this, true)"
   onmouseleave="fn(this, false)"  
     ></div>


0

이 시도:

@keyframe in {
from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
@keyframe out {
from {
    transform: rotate(360deg);
  }
  to {
    transform: rotate(0deg);
  }
}

Firefox 5 이상, IE 10 이상, Chrome, Safari 4 이상, Opera 12 이상에서 지원


0

여기에서 몇 가지 솔루션을 시도했지만 완벽하게 작동하는 것은 없습니다. 그런 다음 https://greensock.com/ 에서 GSAP 를 찾기 위해 웹을 조금 더 검색했습니다 (라이센스에 따라 다르지만 꽤 관대함). 일단 lib를 참조하면 ...

 <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.2.4/gsap.min.js"></script>

... 당신은 갈 수 있습니다:

  var el = document.getElementById('divID');    

  // create a timeline for this element in paused state
  var tl = new TimelineMax({paused: true});

  // create your tween of the timeline in a variable
  tl
  .set(el,{willChange:"transform"})
  .to(el, 1, {transform:"rotate(60deg)", ease:Power1.easeInOut});

  // store the tween timeline in the javascript DOM node
  el.animation = tl;

  //create the event handler
  $(el).on("mouseenter",function(){
    //this.style.willChange = 'transform';
    this.animation.play();
  }).on("mouseleave",function(){
     //this.style.willChange = 'auto';
    this.animation.reverse();
  });

그리고 완벽하게 작동합니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.