Programing

jQuery를 사용하여 div가 스크롤을 부드럽게 따르도록 만드는 방법은 무엇입니까?

crosscheck 2020. 11. 23. 07:46
반응형

jQuery를 사용하여 div가 스크롤을 부드럽게 따르도록 만드는 방법은 무엇입니까?


내 컨테이너에는 섹션 / 상자가 있지만 다른 상자가 보이지 않으면이 상자 중 마지막 상자가 스크롤을 따라야 합니다.

따라서 사용자가 아래로 스크롤하면 일반 사이드 바가 표시되지만 사용자가 충분히 아래로 내려 가면 사이드 바가 종료되지만 마지막 상자가 화면 상단에 이어지기 시작합니다. 나는 이것을 다른 종류의 사이트에서 많이 보았다.

현재 내 코드 :

$(window).scroll(function(){
    $.each($('.follow-scroll'),function(){
        var eloffset = $(this).offset();
        var windowpos = $(window).scrollTop();
        if(windowpos<eloffset.top) {
            var finaldestination = 0;
        } else {
            var finaldestination = windowpos;
        }
        $(this).stop().animate({'top':finaldestination},200);
    });
});

이 질문은 많은 조회수를 얻고 있으며 가장 많이 득표 한 답변에 링크 된 튜토리얼이 오프라인 인 것처럼 보이기 때문에이 스크립트를 정리하는 데 시간이 걸렸습니다.

여기에서 라이브보기 : JSFiddle

자바 스크립트 :

(function($) {
    var element = $('.follow-scroll'),
        originalY = element.offset().top;

    // Space between element and top of screen (when scrolling)
    var topMargin = 20;

    // Should probably be set in CSS; but here just for emphasis
    element.css('position', 'relative');

    $(window).on('scroll', function(event) {
        var scrollTop = $(window).scrollTop();

        element.stop(false, false).animate({
            top: scrollTop < originalY
                    ? 0
                    : scrollTop - originalY + topMargin
        }, 300);
    });
})(jQuery);

https://web.archive.org/web/20121012171851/http://jqueryfordesigners.com/fixed-floating-elements/에 환상적인 jQuery 튜토리얼이 있습니다 .

Apple.com 쇼핑 카트 유형의 사이드 바 스크롤을 복제합니다. 당신에게 잘 제공되었을 수있는 구글 쿼리는 "고정 플로팅 사이드 바"입니다.


솔루션은 다음과 같이 요약 할 수 있습니다.

var el=$('#follow-scroll');
var elpos=el.offset().top;
$(window).scroll(function () {
    var y=$(this).scrollTop();
    if(y<elpos){el.stop().animate({'top':0},500);}
    else{el.stop().animate({'top':y-elpos},500);}
});

el클래스별로 하나의 요소를 찾는 것이 좋은 습관이 아니기 때문에 과제를 변경 했습니다. 하나의 요소 만 ID로 찾으려면 요소 컬렉션을 반복하려면 클래스별로 찾습니다.

참고하십시오-여기에서 내 대답은 당시 허용 된 대답을 나타냅니다 (현재는 여전히 허용되는 대답이지만 그 이후로 편집되었으므로 @Martti Lane의 대답에서 볼 수있는 내용이 더 이상 "보이지 않습니다". 페이지; 내 대답은 "보일드 다운"그의 원본, 수락 된, 대답; 내가 "보일드 다운"한 것에 관심이 있다면 @Martti의 답변 편집 기록을 살펴볼 수 있습니다.)


이것은 나를 위해 매력처럼 작동했습니다.

자바 스크립트 :

$(function() { //doc ready
    if (!($.browser == "msie" && $.browser.version < 7)) {
        var target = "#floating", top = $(target).offset().top - parseFloat($(target).css("margin-top").replace(/auto/, 0));
        $(window).scroll(function(event) {
            if (top <= $(this).scrollTop()) {
                $(target).addClass("fixed");
            } else {
                $(target).removeClass("fixed");
            }
        });
    }
});

CSS :

#floating.fixed{
    position:fixed;
    top:0;
}

출처 : http://jqueryfordesigners.com/fixed-floating-elements/


이것이 제 최종 코드입니다. .... 나를 괴롭힌 것은 위로 스크롤하고 아래로 스크롤하는 것입니다 ... :)

항상 jquery가 어떻게 우아 할 수 있는지 궁금해합니다!

$(document).ready(function(){

    //run once
    var el=$('#scrolldiv');
    var originalelpos=el.offset().top; // take it where it originally is on the page

    //run on scroll
     $(window).scroll(function(){
        var el = $('#scrolldiv'); // important! (local)
        var elpos = el.offset().top; // take current situation
        var windowpos = $(window).scrollTop();
        var finaldestination = windowpos+originalelpos;
        el.stop().animate({'top':finaldestination},500);
     });

});

다음은 내 솔루션입니다 ( 플러그 앤 플레이도 충분하기를 바랍니다 ).

  1. JS 코드 부분 복사
  2. 원하는 요소에 'slide-along-scroll'클래스 추가
  3. JS 코드에서 픽셀 단위로 완벽하게 수정
  4. 당신이 그것을 즐기기를 바랍니다!

// SlideAlongScroll
var SlideAlongScroll = function(el) {
  var _this = this;
  this.el = el;
  // elements original position
  this.elpos_original = el.parent().offset().top;  
  // scroller timeout
  this.scroller_timeout;
  // scroller calculate function
  this.scroll = function() {
    // 20px gap for beauty
    var windowpos = $(window).scrollTop() + 20;
    // targeted destination
    var finaldestination = windowpos - this.elpos_original;
    // define stopper object and correction amount
    var stopper = ($('.footer').offset().top); // $(window).height() if you dont need it
    var stophere = stopper - el.outerHeight() - this.elpos_original - 20;
    // decide what to do
    var realdestination = 0;
    if(windowpos > this.elpos_original) {
      if(finaldestination >= stophere) {
        realdestination = stophere;
      } else {
        realdestination = finaldestination;
      }
    }
    el.css({'top': realdestination });
  };
  // scroll listener
  $(window).on('scroll', function() {
    // debounce it
    clearTimeout(_this.scroller_timeout);
    // set scroll calculation timeout
    _this.scroller_timeout = setTimeout(function() { _this.scroll(); }, 300);
  });
  // initial position (in case page is pre-scrolled by browser after load)
  this.scroll();
};
// init action, little timeout for smoothness
$(document).ready(function() {
  $('.slide-along-scroll').each(function(i, el) {
    setTimeout(function(el) { new SlideAlongScroll(el); }, 300, $(el));
  });
});
/* part you need */
.slide-along-scroll {
  padding: 20px;
  background-color: #CCCCCC;
	transition: top 300ms ease-out;
	position: relative;
}
/* just demo */
div {  
  box-sizing: border-box;
}
.side-column {
  float: left;
  width: 20%;    
}
.main-column {
  padding: 20px;
  float: right;
  width: 75%;
  min-height: 1200px;
  background-color: #EEEEEE;
}
.body {  
  padding: 20px 0;  
}
.body:after {
  content: ' ';
  clear: both;
  display: table;
}
.header {
  padding: 20px;
  text-align: center;
  border-bottom: 2px solid #CCCCCC;  
}
.footer {
  padding: 20px;
  border-top: 2px solid #CCCCCC;
  min-height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="header">
      <h1>Your super-duper website</h1>
  </div>
  <div class="body">  
    <div class="side-column">
        <!-- part you need -->
        <div class="slide-along-scroll">
            Side menu content
            <ul>
               <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
               <li>Aliquam tincidunt mauris eu risus.</li>
               <li>Vestibulum auctor dapibus neque.</li>
            </ul>         
        </div>
    </div>
    <div class="main-column">
        Main content area (1200px)
    </div>
  </div>
  <div class="footer">
      Footer (slide along is limited by it)
  </div>
</div>


이 코드는 잘 작동하지 않습니다. 조금 수정했습니다.

var el = $('.caja-pago');
var elpos_original = el.offset().top;

 $(window).scroll(function(){
     var elpos = el.offset().top;
     var windowpos = $(window).scrollTop();
     var finaldestination = windowpos;
     if(windowpos<elpos_original) {
         finaldestination = elpos_original;
         el.stop().animate({'top':400},500);
     } else {
         el.stop().animate({'top':windowpos+10},500);
     }
 });

특정 개체에 도달하면 div가 중지해야했기 때문에 다음과 같이했습니다.

var el = $('#followdeal');
    var elpos_original = el.offset().top;
    $(window).scroll(function(){
        var elpos = el.offset().top;
        var windowpos = $(window).scrollTop();
        var finaldestination = windowpos;
        var stophere = ( $('#filtering').offset().top ) - 170;
        if(windowpos<elpos_original || windowpos>=stophere) {
            finaldestination = elpos_original;
            el.stop().animate({'top':10});
        } else {
            el.stop().animate({'top':finaldestination-elpos_original+10},500);
        }
    });

이것은 페이스 북에서도 동일합니다 :

<script>
var valX = $(window).scrollTop();
function syncScroll(target){
	var valY = $(window).scrollTop();
	var difYX = valY - valX;
	var targetX = $(target).scrollTop();
	if(valY > valX){
		$(target).scrollTop(difYX);
	}
	if(difYX <= 0){
		$(target).scrollTop(-20);
	}
}

$(window).scroll(function(){
	syncScroll('#demo');
})
</script>
body{
  margin:0;
  padding:0;
  height:100%;
}
#demo{
  position:fixed;
  height:100vh;
  overflow:hidden;
  width:40%;
}
#content{
  position:relative;
  float:right;
  width:60%;
  color:red; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="demo">
    <ul>
      <li>
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
      </li>
      <li>
        <p>
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
        </p>
      </li>  
      <li>
        <p>
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
        </p>
      </li>
    <ul>
  </div>
  <div id="content">
    <ul>
      <li>
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
      </li>
      <li>
        <p>
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
        </p>
      </li>  
      <li>
        <p>
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
        </p>
      </li>
      <li>
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
      </li>
      <li>
        <p>
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
        </p>
      </li>  
      <li>
        <p>
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
        </p>
      </li>
      <li>
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
      </li>
      <li>
        <p>
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
        </p>
      </li>  
      <li>
        <p>
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
        </p>
      </li>
      <li>
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
      </li>
      <li>
        <p>
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
        </p>
      </li>  
      <li>
        <p>
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
        </p>
      </li>
    <ul>
   </div>   
</body


나는 이것에 대해 비교적 간단한 대답을 썼습니다.

내 페이지의 특정 div 바로 아래에 고정하기 위해 "고정 테이블 헤더"플러그인 중 하나를 사용하는 테이블이 있지만 테이블 왼쪽의 메뉴가 고정되지 않았습니다 (테이블의 일부가 아니므로).

내 목적을 위해 "고정"이 필요한 div가 항상 창 상단에서 385 픽셀 아래에서 시작된다는 것을 알았으므로 바로 위에 빈 div를 만들었습니다.

<div id="stopMenu" class="stopMenu"></div>

그런 다음 이것을 실행했습니다.

$(window).scroll(function(){   
   if ( $(window).scrollTop() > 385 ) {
    extraPadding = $(window).scrollTop() - 385;
    $('#stopMenu').css( "padding-top", extraPadding );
   } else {
     $('#stopMenu').css( "padding-top", "0" );
   }
});

As the user scrolls, it adds whatever the value of $(window).scrollTop() is to the integer 385, then adds that value to the stopMenu div that's above the thing I want to stay focused.

In the event the user scrolls all the way back up, I just set the extra padding to 0.

This doesn't require the user to do anything IN CSS particularly, but it's kind of a nice effect to make a small delay, so I put the class="stopMenu" in as well:

.stopMenu {
  .transition: all 0.1s;
}

참고URL : https://stackoverflow.com/questions/2177983/how-to-make-div-follow-scrolling-smoothly-with-jquery

반응형