CSS Transition
2023. 9. 20. 18:30ㆍInteractive Web
duration
- 초단위
transition time function
- ease(default)
- ease-in
- ease-out
- ease-in-out
- linear
transition property(값 자체가 숫자 value인 것들만 적용)
- transform
- background-color
- width
- height
- etc..
delay(값만큼 지연되었다가 재생)
- 초단위
박스 클릭시 오른쪽으로 1초간 300px 좌우 이동하며 색상 coral에서 블루로 변경
<style>
.box {
width: 100px;
height: 100px;
background: coral;
transition: 1s;
}
.box-action {
transform: translateX(300px);
background: blue;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
const box = document.querySelector(".box");
box.addEventListener("click", () => {
box.classList.toggle("box-action");
});
</script>
transition: 1s 2s;
일땐 2초 delay
색상에는 transition을 안주고 transform에만 주고싶다면
transition: transform 1s;
transform, background에 각각 다른 transition을 주고싶다면
.box {
transtion:
transform 1s ease-in,
background 2s 1s linear;
}
Transition Event
- transitionstart
- transitionend
- transitionrun
- transitioncancel
box.addEventListener("transitionstart", (e) => {
console.log(`${e.propertyName}`);
});
박스아래 메세지를 주고싶을땐
<script>
const box = document.querySelector(".box");
const message = document.querySelector('.message');
box.addEventListener("click", () => {
box.classList.toggle("box-action");
});
box.addEventListener("transitionstart", (e) => {
console.log(`${e.propertyName}`);
message.innerText = 'START';
});
</script>
SVG에 Transition 적용하기
img태그 대신 object태그를 사용하면 요소 하나하나를 객체로 인식하고 스크립트로 컨트롤 가능하다.
<img class="hand" src="images/hand.svg" alt="Hand">
<object class="key" data="images/key.svg" type="image/svg+xml"></object>

<style>
.key-blade {
transition: 0.5s;
}
.key-blade-flipped {
transform: rotate(-180deg);
transform-origin: 219.59px 211.59px;
}
.key-blade-flipped {
transform: rotate(0);
}
</style>
<script>
const keyBtn = document.querySelector('.key-btn');
const keyBlade = document.querySelector('.key-blade');
keyBtn.addEventListener('click', () => {
keyBlade.classList.toggle('key-blade-flipped');
});
</script>
getBoundingClientRect()라는 메서드를 사용하면 객체의 크기와 위치를 가져올 수 있다.
const hand = document.querySelector('.hand');
const key = document.querySelector('.key');
let isKeyInHand = false;
hand.addEventListener('click', () => {
if (isKeyInHand) {
key.style.transform = 'scale(1) translate(0, 0);
} else {
const handRect = hand.getBoundingClientRect();
const leftPosition = handRect.left + 150;
const topPosition = handRect.top - 60;
hand.style.transform = `scale(0.5) translate(${leftPosition}px, ${topPosition}px`;
}
});
key.addEventListener('transitioned', () => {
isKeyInHand = !isKeyInHand;
});
*인프런 1분코딩님의 웹 애니메이션의 새로운 표준, Web Animations강의를 참고하였습니다.
'Interactive Web' 카테고리의 다른 글
CSS Animation (0) | 2023.09.20 |
---|---|
css-flex (0) | 2022.07.16 |
css-3D (0) | 2022.07.16 |
CSS transition, transform, and animation (0) | 2022.06.18 |