[프로젝트] 인스타그램 클론코딩 #5. JS 적용하기

UkiUkhui·2022년 8월 19일
0

Project 해보자!

목록 보기
6/8

5. JS

vscode

  • html이 갑자기 인식 안됨
    : 기본설정 > setting > files : associations 확인
  • 확인결과 .html 이 js로 되어 있어서 인식이 안됨
  • js코드의 경우 index와 연결되므로 단독 실행 시 document 정의가 안되어있다고 뜸.
    • 실제로 index.html 실행하면 정상 작동함
      로그 확인은 chrome 개발자 도구 열어서 log 확인
  • js코드 미작동 : html header부에 script 코드 미삭제

1) 하트 색상 변경

  • index.html
</section>
        <script src="js/main.js"></script>
    </body>

</html>
  • main.js
const heart = document.querySelector('.heart_btn'); //하트요소

heart.addEventListener('click', function () {
    heart.classList.toggle('on'); //하트 누르면 on 클래스 추가
})
  • style.css
.heart_btn.on .sprite_heart_icon_outline{/*on 클래스 추가 시 이미지 변경*/
    background: url('../imgs/background01.png') no-repeat -26px -261px;
}
  • querySelector : 쿼리 1개만 가지고 오므로 이후 게시물에서는 하트 실행 안됨
    • querySelectorAll() 사용해도 배열로 가져오므로 하나하나 이벤트를 넣어야 함
      • 해결 : event delegation

2) 스크롤 이벤트 추가

  • 스크롤할때마다 숫자가 바뀌도록 함
    • 윈도우 객체에 이벤트 추가
    • 스크롤 대상 : 브라우저
    • pageYOffset > 10인 경우 header 고정하여 같이 이동하도록 함
    • 스크롤 시 인스타그램 로고 사라지도록 하는 기능 추가
#header.on {
    position: fixed;
}

#header .inner{/*inner 내 컨텐츠를 넣으면 안에 값이 들어옴*/
    width: 975px;
    height: 77px;/*높이 값은 header내의 자식들에게 줌*/
    margin: 0 auto; /*가운데 정렬*/
    display: flex;/*가로 배치*/
    justify-content: space-between;/*x축 정렬:공간 자동 분배*/
    align-items: center;/*y축 정렬*/
    transition: all 1s;/*자연스러운효과*/
}

#header.on .inner{
    height: 52px;
}

#header .inner  .logo   .sprite_insta_icon:after{
    content: '';/*공백을 받아옴*/
    width: 1px;
    height: 28px;
    background: #000;
    position: absolute; /*부모 기준으로 위치 잡음*/
    right: -15px;
    top: -4px;
    transition: all .5s;/*자연스러운효과*/
}

#header .inner .logo div:nth-child(2){
    transform:translateY(2px);
    transition: all .5s;/*자연스러운효과*/
}

#header.on .inner .logo .sprite_insta_icon:after{
    opacity: 0;
}

#header.on .inner .logo div:nth-child(2){
    opacity: 0;
}

const heart = document.querySelector('.heart_btn');//단독실행하면 안됨
const header = document.querySelector('#header');

heart.addEventListener('click', function () {
    console.log('하트누름 정상작동');
    heart.classList.toggle('on');
});

function scrollFunc(){
    console.log(pageYOffset);
    if(pageYOffset >= 10){
        header.classList.add('on');
    }else{
        header.classList.remove('on');
    }
}

window.addEventListener('scroll', scrollFunc);


3) 사이드박스 스크롤 이벤트 추가


const heart = document.querySelector('.heart_btn');//단독실행하면 안됨
const header = document.querySelector('#header');
const sidebox = document.querySelector('.side_box');

heart.addEventListener('click', function () {
    console.log('하트누름 정상작동');
    heart.classList.toggle('on');
});

function resizeFunc() {
    if (pageYOffset >= 10) {
        let calcWidth = (window.innerWidth * 0.5) + 167; //웹페이지 기반 위치 재조정
        sidebox.style.left = calcWidth + 'px';
    }
}

function scrollFunc() {
    console.log(pageYOffset);
    if (pageYOffset >= 10) {
        header.classList.add('on');
        sidebox.classList.add('on');
    } else {
        header.classList.remove('on');
        sidebox.classList.remove('on');
        sidebox.removeAttribute('style');
    }
}

window.addEventListener('scroll', scrollFunc);

  • position:fixed
    • 기준점을 무조건 브라우저로 잡음
    • inner 기준으로 잡고 있던 side_box가 fixed로 변경되면 브라우저를 기준으로 잡게 되면서 이상한 위치로 이동
  • 스크롤 내리게 되었을 때 위치 재조정 필요 = resizeFunc
    • css : 스크롤에 따라 고정되어 이동하기 위해 position:fixed 사용
      • 웹페이지 기준
    • 레이아웃 기반으로 위치 정해진 side_box 위치 재지정 필요

function resizeFunc() {
    if (pageYOffset >= 10) {
        let calcWidth = (window.innerWidth * 0.5) + 167; //웹페이지 기반 위치 재조정
        sidebox.style.left = calcWidth + 'px';
    }
}

function scrollFunc() {
    console.log(pageYOffset);
    if (pageYOffset >= 10) {
        header.classList.add('on');
        sidebox.classList.add('on');
        resizeFunc();

4) 화면 축소에 따른 리사이즈 이벤트 추가

  • 화면 크기 < 컨텐츠박스 : 컨텐츠박스가 그에 맞게 줄어들도록 이벤트 작성
    • 컨텐츠들이 좌우값이 리사이즈하게 되면 화면크기에 맞춰 좌우값이 유지되도록 만듦
function resizeFunc() {
    if (pageYOffset >= 10) {
        let calcWidth = (window.innerWidth * 0.5) + 167; //웹페이지 기반 위치 재조정
        sidebox.style.left = calcWidth + 'px';
    }

    if(matchMedia('screen and (max-width : 800px)').matches){
        //여러 개의 컨텐츠 박스가 있으므로 배열 활용
        for(let i=0; i<variableWidth.length;i++){
            variableWidth[i].style.width = window.innerWidth - 20 + 'px';
        }
    }else{
        for(let i=0; i<variableWidth.length;i++){
            variableWidth[i].removeAttribute('style');
        }
    }
}

  • width <= 800
    • element.style값이 width값 조정
    • 그 이상인 경우 style값 사라짐
profile
hello world!

0개의 댓글