네이버 카페에 워드프레스 아바다 테마를 사용하는 사이트에서 앵커로 이동하는 링크 클릭 시 부드럽게 이동하지 않고 클릭과 동시에 이동하는 문제에 관한 질문이 최근 올라온 적이 있습니다.
부드럽게 앵커로 이동하도록 하고 싶은 경우 scroll-behavior 속성을 사용할 수 있습니다.
부드러운 스크롤 - scroll-behavior 속성
기본적으로 다음과 같은 CSS 코드를 추가하면 앵커 이동 시 부드럽게 이동할 것입니다.
html {
scroll-behavior: smooth;
}
워드프레스의 경우 워드프레스 관리자 페이지 » 외모 » 사용자 정의하기 » 추가 CSS에 추가하시면 됩니다.
실제로 아바다 테마에서 이 코드를 적용 시 부드럽게 잘 작동하는 것을 확인할 수 있었습니다. scroll-behavior 속성은 크롬 61.0 이상, 엣지 브라우저 79.0 이상, 파이어폭스 36.0 이상 버전 등에서 지원됩니다.
다만, scroll-behavior 속성 사용 시 스크롤 시간 간격은 조정할 수 없다고 합니다. 스크롤 지속 시간을 설정하려면 자바스크립트를 이용해야 합니다. 예를 들어, 다음과 같은 JavaScript 코드로 테스트해 볼 수 있습니다.
<script>
function scrollToAnchor(anchorId, duration) {
const anchor = document.getElementById(anchorId);
if (!anchor) return;
const startPosition = window.pageYOffset;
const targetPosition = anchor.getBoundingClientRect().top + startPosition;
const startTime = performance.now();
function animateScroll(currentTime) {
const elapsedTime = currentTime - startTime;
const progress = Math.min(elapsedTime / duration, 1);
// Use an easing function to make the scroll smoother
const easeInOutQuad = (t) => t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
const easedProgress = easeInOutQuad(progress);
window.scrollTo(0, startPosition + (targetPosition - startPosition) * easedProgress);
if (progress < 1) {
requestAnimationFrame(animateScroll);
}
}
requestAnimationFrame(animateScroll);
}
document.addEventListener('DOMContentLoaded', function () {
const anchorLinks = document.querySelectorAll('a[href^="#"]:not([href="#"])');
anchorLinks.forEach(link => {
link.addEventListener('click', (event) => {
event.preventDefault();
const anchorId = link.getAttribute('href').substring(1);
scrollToAnchor(anchorId, 1000); // One-second duration for all anchor links
});
});
});
</script>
참고
https://avada.tistory.com/2684
https://avada.tistory.com/2897