-
카테고리
-
세부 분야
웹 개발
-
해결 여부
해결됨
스크립트 관련 질문이 있습니다.
20.12.04 17:07 작성 조회수 212
0
style 로 값을 준 후에
addEventListener('transitionend') 이벤트를 주려고 합니다.
end가 붙어있으면 제거해주고
없으면 end 추가해주는 식으로 했는데..
처음 클릭했을 때 end 클래스가 계속 보여졌다 사라졌다 합니다ㅠㅠㅠㅠ
if 문 안에 return; 을 적용했는데도 동일한 현상이 보여집니다ㅠㅠ
const ballElem = document.querySelector('.ball');
let defult = false;
window.addEventListener('click', function(e) {
ballElem.style.transform = 'translate(' + (e.clientX - 15) +'px, ' + (e.clientY - 15) + 'px)';
ballElem.addEventListener('transitionend', function(e) {
if ( !defult ) {
ballElem.classList.add('end');
defult = true;
return;
} else if ( defult) {
ballElem.classList.remove('end');
defult = false;
return;
}
});
});
답변을 작성해보세요.
2
1분코딩
지식공유자2020.12.07
end 클래스가 추가되면 빨강 -> 파랑으로 트랜지션이 일어나고,
end 클래스가 제거되면 파랑 -> 빨강으로 트랜지션이 일어나죠?
즉 end 클래스가 추가되든 제거되든, 무조건 계속 transitionend 이벤트가 일어나서 무한 반복되는 현상입니다.
transitionend 대신 setTimeout으로 아래처럼 해보세요^^
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Transition/Animation Event</title>
<style>
.ball {
position: absolute;
left: 0;
top: 0;
width: 30px;
height: 30px;
border-radius: 50%;
background: red;
transition: 2s;
}
.ball.end {
background: dodgerblue;
}
</style>
</head>
<body>
<div class="ball"></div>
<script>
const ballElem = document.querySelector('.ball');
let colorState = false;
let clickable = true;
window.addEventListener('click', function (e) {
ballElem.style.transform = 'translate(' + (e.clientX - 15) + 'px, ' + (e.clientY - 15) + 'px)';
if (!clickable) return;
clickable = false;
setTimeout(function () {
if (!colorState) {
ballElem.classList.add('end');
colorState = true;
} else {
ballElem.classList.remove('end');
colorState = false;
}
clickable = true;
}, 2000);
});
</script>
</body>
</html>
0
답변 2