이미지 슬라이드로 넘기기
<script>
const container = document.querySelector(".container");
const prevBtn = document.querySelector(".prev");
const nextBtn = document.querySelector(".next");
(function addEvent(){
prevBtn.addEventListener('click', translateContainer.bind(this, 1));
nextBtn.addEventListener('click', translateContainer.bind(this, -1));
})();
function translateContainer(direction){
const selectedBtn = (direction === 1) ? 'prev' : 'next';
container.style.transitionDuration = '500ms';
container.style.transform = `translateX(${direction * (100 / 5)}%)`;
container.ontransitionend = () => reorganizeEl(selectedBtn);
}
function reorganizeEl(selectedBtn) {
container.removeAttribute('style');
(selectedBtn === 'prev') ? container.insertBefore(container.lastElementChild, container.firstElementChild): container.appendChild(container.firstElementChild);
}
</script>
<script>
// 텍스트 타이핑 효과
// span 요소 노드 가져오기
const spanEl = document.querySelector("main h2 span");
const txtArr = ['Web Publisher', 'Front-End Developer', 'Web UI Designer', 'UX Designer', 'Back-End Developer']; // 화면에 표시할 문장 배열
let index = 0; // 배열의 인덱스 초깃값
let currentTxt = txtArr[index].split(""); // 화면에 표시할 문장 배열에서 요소를 하나 가져온 뒤, 배열로 만들기
// 실행결과 ['W', 'e', 'b', ' ', 'P', 'u', 'b', 'l', 'i', 's', 'h', 'e', 'r']
// 텍스트가 입력되는 효과의 핵심은 currentTxt 변수에 할당된 배열 요소를 앞에서부터 한 개씩 출력하는 것입니다. 그러면 마치 텍스트가 한 글자씩 작성되는 것처럼 보이게 됩니다. 이를 위해 다음처럼 writeTxt() 함수를 만들어 배열 요소를 한 개씩 출력하게 합니다.
function writeTxt(){
spanEl.textContent += currentTxt.shift();
if(currentTxt.length !== 0){
setTimeout(writeTxt, Math.floor(Math.random() * 100));
}else{
currentTxt = spanEl.textContent.split("");
setTimeout(deleteTxt, 3000);
}
}
writeTxt();
// 텍스트를 삭제할 때, 뒤에서부터 요소를 추출해 한 글자씩 줄어드는 것처럼 표현
function deleteTxt(){
currentTxt.pop(); // ①
spanEl.textContent = currentTxt.join("");// ②
if(currentTxt.length !== 0){ // ③
setTimeout(deleteTxt, Math.floor(Math.random() * 100));
}else{ // ④
index = (index + 1) % txtArr.length;
currentTxt = txtArr[index].split("");
writeTxt();
}
}
</script>
웹 브라우저를 스크롤하면 헤더 영역에 새로운 클래스를 추가해 디자인을 변경합니다.
<script>
// 웹 브라우저의 수직 스크롤 위치는 window 객체의 pageYOffset 속성으로 참조할 수 있습니다.
// 속성값이 0보다 크면 스크롤됐다고 볼 수 있으므로 이를 조건으로 처리해서 if 문으로 active 클래스를 추가하거나 삭제하면 됩니다.
// pageYOffset : 스크롤했을 때 화면이 수직으로 이동하는 픽셀 수
const headerEl = document.querySelector("header");
window.addEventListener('scroll', function(){
const browerScrollY = window.pageYOffset;
if(browerScrollY > 0){
headerEl.classList.add("active"); //명시된 클래스를 추가하는 메서드
}else{
headerEl.classList.remove("active"); //명시된 클래스를 제거하는 메서드
}
});
</script>
헤더 메뉴를 클릭하면 페이지 내부의 다른 영역으로 부드럽게 스크롤이 이동합니다.
<script>
// 이번에는 헤더 영역의 메뉴를 클릭하면 메뉴 영역으로 스크롤이 부드럽게 이동하는 효과를 자바스크립트로 작성해 보겠습니다.
// Window 객체의 scrollTo() 메서드에서 behavior 속성을 사용하면 애니메이션 효과를 적용해 스크롤을 부드럽게 이동할 수 있습니다. 단, IE나 iOS 모바일에서는 제대로 동작하지 않습니다. 이 외의 웹 브라우저에서는 정상적으로 작동합니다.
// 일단 이동할 대상 요소를 가리키는 선택자(selector)를 매개변수에 전달받아 이동하려는 대상의 현재 위칫값을 구하는 코드를 작성합니다.
/* 애니메이션 스크롤 이동 */
const animationMove = function(selector){
// ① selector 매개변수로 이동할 대상 요소 노드 가져오기
const targetEl = document.querySelector(selector);
// ② 현재 웹 브라우저의 스크롤 정보(y 값)
const browserScrollY = window.pageYOffset;
// ③ 이동할 대상의 위치(y 값) https://developer.mozilla.org/ko/docs/Web/API/Element/getBoundingClientRect
//getBoundingClientRect(): 윈도우(window)룰 기준으로 특정 엘리먼트의 위치 값을 구하는 방법
const targetScorllY = targetEl.getBoundingClientRect().top + browserScrollY;
// ④ 스크롤 이동 https://salgum1114.github.io/css/2019-04-28-scroll-behavior-smooth/
window.scrollTo({ top: targetScorllY, behavior: 'smooth' });
};
// 코드가 조금 복잡해 보일 수 있지만, 부드러운 스크롤 이동 효과를 구현하는 데 꼭 필요한 값들입니다. 웹 브라우저의 스크롤 이동을 처리하려면 이동할 대상의 스크롤 위치(y 값)를 당연히 알아야 합니다. 그러려면 이동할 대상의 노드를 가져올 수 있어야 하고(①), 현재 웹 브라우저의 스크롤 위치를 구해야 합니다(②). 그래야 가져온 요소 노드로 구하는 위치의 정확한 y 값을 구할 수 있습니다(③). 그리고 window 객체의 scrollTo() 메서드를 사용해 해당 위치로 이동합니다(④).
// 이제 기존 헤더 영역에서 메뉴에 해당하는 button 태그에 클릭 이벤트를 연결해 앞에서 만든 animationMove() 함수를 실행하겠습니다. 헤더 영역의 메뉴에 사용된 button 태그에 click 이벤트를 연결하기 위해 다음처럼 코드를 수정합니다.
// https://developer.mozilla.org/ko/docs/Learn/HTML/Howto/Use_data_attributes
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
// 스크롤 이벤트 연결하기
const scollMoveEl = document.querySelectorAll("[data-animation-scroll='true']");
for(let i = 0; i < scollMoveEl.length; i++){
scollMoveEl[i].addEventListener('click', function(e){
const target = this.dataset.target;
animationMove(target);
});
}
</script>
오늘은 지금까지 배웠던 HTML, CSS, JS를 모두 사용해서 홈페이지를 만들어보았다. 오랜만에 CSS 작성을 하니까 한결 편안한 느낌이 들었다ㅎㅎ
css 부분은 내용도 많고해서 생략을 해서 적었고, 다시 복습이 필요한 js부분을 적어놓았다. 자바스크립트 학습기간이 끝나서 전체적으로 모아서 다시 복습을 해봐야겠다.