본문 바로가기
Js

scroll, resize, offset().top

by 영감은어디에 2024. 6. 30.

1

$(window).resize(function(){
    if($(window).width() > 768){
        $(".gnb").show();
    }else{
        $(".gnb").hide();
    }
});

$(window).scroll(function(){
    if($(this).scrollTop() > 0){
        $header.addClass("sticky");

        var $infoTh = $infos.offset().top - 300;
        var $infoEx = false;
        if(!$infoEx){
            if($(this).scrollTop() > $infoTh){
                $infos.addClass("active");
                $infoEx = true;
            }
        }

    } else{
        $header.removeClass("sticky");
    }
  
});

2

window.scrollY();  // 스크롤한 양
window.scrollTo(0, 100); // 강제로 100
window.scrollBy(0, 100) // 현재위치에서 100


window.addEventListener("scroll", function () {
    var th = window.scrollY;
    if (th > 150) {
        document.querySelector(".navbar-brand").classList.add("small");
    } else {
        document.querySelector(".navbar-brand").classList.remove("small");
    }

    // 페이지 로딩막대
    var thm = document.querySelector("html").scrollTop;
    var thmbox = document.querySelector("html").clientHeight;
    var thmsr = document.querySelector("html").scrollHeight;
    var thmwidth = (thm / (thmsr - thmbox)) * 100 + "%";
    document.querySelector(".redbox").style.width = thmwidth;
    console.log(thm, thmbox, thmsr, thmwidth);
});

// 약관 다 읽었니
document.querySelector(".agree").addEventListener("scroll", function () {
    // th2 window 아닐때 scrollTop
    // th2box 실제 박스 높이
    // th2sr실제 스크롤 높이
    var th2 = document.querySelector(".agree").scrollTop;
    var th2box = document.querySelector(".agree").clientHeight;
    var th2sr = document.querySelector(".agree").scrollHeight;

    if (th2 + th2box + 10 >= th2sr) {
        alert("약관 다 읽었음");
    }
    console.log(th2, th2box, th2sr);
});
//부트스트랩 사용시 자동 스크롤 css수정
:root {scroll-behavior:auto;}

//scroll은 로드 된 뒤에 실행, 1초에 60번 움직임
document.querySelector('html').scrollHeight; //페이지 높이
document.documentElement.scrollHeight; //페이지 높이
document.querySelector('html').scrolltop; //스크롤한 높이
window.scrollY; //스크롤한 높이
$(window).on('scroll', function(){
	$(window).scrollTop(); //스크롤한 높이
	$(window).scrollTop(100); //100으로 이동
})

3. .offset().top 을 이용한 sticky menu

var windowh = $(window),
    header = $('.header'),
    headerTop = header.offset().top;
    
windowh.scroll(function(){
    if($(this).scrollTop() >= headerTop){
        header.addClass('sticky');
    }else{
        header.removeClass('sticky');
    }
})

'Js' 카테고리의 다른 글

정규표현식  (0) 2024.07.01
setTimeout, setInterval, 이전 다음 슬라이드  (0) 2024.07.01
addClass, 아코디언, tab, attr, each, hasClass  (0) 2024.07.01
addEventListener  (1) 2024.07.01
다크모드 로컬 저장  (0) 2024.06.30
플러그인없이 이미지 슬라이드  (0) 2024.06.30
masonry 메이슨리 레이아웃  (0) 2024.06.30
rect() 를 이용한 마스크 효과  (0) 2024.06.30