밑에 버튼과 카카오 이미지를 position:fixed로 고정시켜 주었다. 스크롤 할 때마다 저 부분은 움직이지 않는거다... 하지만 여기서 문제가 발생하였다.
버튼 같은 경우는 margin:auto와 bottom:5px로 어찌저찌 고정 시켰는데 카카오 이미지가 원하는데로 안 움직이기 시작했다.
분명히 바로 윗 부모의 Width를 고정 시켰지만 밖으로 나가는 것이다.
1.width가 버튼과 똑같은 부모를 생성
2.그 후 안에 카카오 이미지를 넣고 fixed를 줌
3.ㅎㅎ right:0 하면 버튼위로 가겠지??
4.화면 오른쪽 끝으로 이동함...
뭐지... 부모의 width는 정해져있고 right:0을 주면 부모 오른쪽 끝으로 가야하는거 아닌가? 아니다
postion:fixed는 항상 viewport가 부모이다!
그럼 어떻게 했을 까?
1.fixed를 줄 요소들을 다 감싼다.
2.그 감싼 부모에게 fixed를 준다.
3.그 다음 안에 요소들은 position:absolute로 조절해준다.
지금까지 fixed를 쓴적이 없어서 실수를 한 것 같다... 역시 기초부터 천천히!
스크롤을 내리면 상단의 진행바가 움직이는 기능을 구현해보자
ex) https://kgaprogramming.oopy.io/
html
<hr class="progress-bar" id="progree_bar" />
css
.progress-bar{
border: 1px solid rgb(3, 169, 244);
width: 1px;
margin-top: 46px;
position: absolute;
}
알고리즘을 정리하자면
1.처음에 width를 1px로 만든다.
2.스크롤을 내릴 때마다 js로 스크롤의 위치를 변수에 저장한다.
3.그 값을 적절하게 조정해서 progress-bar의 width를 변경하면 끝!
let progree_bar = document.querySelector("#progree_bar");
window.addEventListener("scroll", () => {
let scrollLocation = document.documentElement.scrollTop;
progree_bar.style.width = `${scrollLocation / 5.9}px`;
console.log(scrollLocation);
});
window.addEventListner로 scroll 이벤트를 만든다.
그 후 Template literals를 이용해서 실시간으로 width를 변경시킨다!
위에 명시한 사이트에서 스크롤을 할 때 오른쪽 하단에서 top이 튀어나오는 것을 볼 수 있다. 구현해보자 알고리즘은 다음과 같다.
1.처음 스크롤 값을 변수 a에저장 그 다음 변화 전 a의 값이 돼줄 b에 함수 끝에 a값을 저장
2.if문으로 만약 a가 b보다 크다면 스크롤을 내렸다 판단하여 함수 실행
css
.top {
width: 48px;
height: 48px;
box-shadow: 0 0 4px 4px #d6d6d6;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
border-radius: 50%;
position: fixed;
right: 5px;
bottom: -50px;
transition: all 0.5s;
cursor: pointer;
z-index: 3;
}
js
var beforeScrollLocation = 0;
window.addEventListener("scroll", () => {
let scrollLocation = document.documentElement.scrollTop;
//스크롤을 내릴시
if (beforeScrollLocation > scrollLocation) {
top_button.style.bottom = "40px";
}
//전 스크롤 값을 가져오기 위헤 beforeScrollLocation에 scrollLocation값 저장
beforeScrollLocation = scrollLocation;
});
그 다음 top을 누를시 위로 올려주자
topBtn.addEventListener("click", () => {
window.scrollTo({ top: 0, behavior: "smooth" });
});