Используйте jQuery для прокрутки до нижней части div с большим количеством текста


у меня есть div с полосой прокрутки справа, когда в нем много текста. Я попытался использовать этот код для прокрутки до нижней части div при загрузке страницы, но мне не очень повезло. Как этого можно достичь?

стиль:

div.messageScrollArea{
    width: 100%;
    max-height: 300px;
    overflow: auto;
}

JavaScript код:

$(document).ready(function () {
    var objDiv = $('.messageScrollArea');
    if (objDiv.length > 0){
        objDiv[0].scrollTop = objDiv[0].scrollHeight;
    }
});
8 59

8 ответов:

обращайтесь : .scrollTop(), вы можете попробовать решение здесь : http://jsfiddle.net/y430ovjt/

$(function() {
  var wtf    = $('#scroll');
  var height = wtf[0].scrollHeight;
  wtf.scrollTop(height);
});
 #scroll {
   width: 200px;
   height: 300px;
   overflow-y: scroll;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scroll">
    <br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/> <center><b>Voila!! You have already reached the bottom :)<b></center>
</div>

Edit : для людей, которые ищут немного приятной анимации с прокруткой : http://jsfiddle.net/o98zbx8j

$(function() {
  var height = 0;

  function scroll(height, ele) {
    this.stop().animate({
      scrollTop: height
    }, 1000, function() {
      var dir = height ? "top" : "bottom";
      $(ele).html("scroll to " + dir).attr({
        id: dir
      });
    });
  };
  var wtf = $('#scroll');
  $("#bottom, #top").click(function() {
    height = height < wtf[0].scrollHeight ? wtf[0].scrollHeight : 0;
    scroll.call(wtf, height, this);
  });
});
#scroll {
  width: 300px;
  height: 200px;
  overflow-y: scroll;
}
#bottom,
#top {
  font-size: 12px;
  cursor: pointer;
  min-width: 50px;
  padding: 5px;
  border: 2px solid #0099f9;
  border-radius: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="bottom">scroll to bottom</span>
<br />
<br />
<br />
<div id="scroll">
  <center><b>There's Plenty of Room at the Top, seriously?</b>
  </center>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam at enim dignissim, eleifend eros at, lobortis sem. Mauris vel erat felis. Proin quis convallis neque, quis molestie augue. Vestibulum aliquam elit sit amet venenatis eleifend. Donec dapibus
    mauris ac lorem mattis pulvinar. Curabitur cursus elit commodo tellus bibendum, ut euismod nisi luctus. Pellentesque id magna nunc. Nam luctus nisi sapien, ac porta sem ultrices vitae. Suspendisse aliquet eleifend nunc, in mattis tellus dapibus rutrum.
    Nullam a sem venenatis, suscipit lorem eu, facilisis leo. Nunc eget eleifend magna. Curabitur dictum dui in massa vestibulum sagittis. Mauris sodales neque at tincidunt feugiat. Curabitur iaculis purus nec tortor elementum pulvinar. Donec non mattis
    augue.</p>

  <p>Integer sit amet iaculis nulla. Cras vehicula nunc eu leo aliquet, et convallis erat aliquet. Aenean tempor faucibus justo, porta blandit felis semper at. Maecenas auctor nibh sit amet tellus consectetur, et varius velit iaculis. Phasellus convallis
    lacinia dapibus. Praesent tempus nunc elit, id volutpat tellus sagittis commodo. Vestibulum ultrices quam vel congue viverra. Integer varius diam quis tempor consequat. Integer pulvinar neque lorem, eu lobortis augue pharetra vel. Praesent ornare
    lacus quis nisi fermentum dignissim. Curabitur hendrerit augue eu interdum interdum.</p>

  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam a ex non dolor rutrum suscipit vitae sit amet nibh. Donec pulvinar odio non ultrices dignissim. Quisque in risus lobortis, accumsan ante et, pellentesque
    erat. Quisque ultricies tortor sed tortor venenatis posuere. Integer convallis nunc ut tellus sagittis, et imperdiet erat volutpat. Sed non maximus augue. Sed mattis ipsum sed sem rutrum, at mollis ligula facilisis. Etiam fringilla hendrerit mi eu
    molestie. Etiam semper feugiat nunc, eu pellentesque metus porta pretium. Duis tempor neque ut libero scelerisque euismod. Vivamus molestie, quam a mattis scelerisque, dolor turpis accumsan quam, a cursus sem quam at ex. Suspendisse congue elit quis
    sem scelerisque commodo.</p>

  <p>Ut eu odio at urna hendrerit ullamcorper. Nulla ut turpis molestie diam aliquet luctus. Curabitur dignissim tellus ut porta sagittis. Vivamus ut erat ut neque consequat interdum. Duis vitae risus eget arcu pulvinar venenatis. Maecenas erat arcu, hendrerit
    id tortor ut, viverra elementum nibh. Nam quis metus sit amet lacus rhoncus porttitor ac non ipsum. Nullam lacus dui, tempus sed elementum ut, venenatis eget ipsum. Quisque blandit maximus enim eu porta.</p>

  <p>Donec mollis diam eros, eu ultrices magna sollicitudin vitae. Nullam quam sapien, elementum a metus nec, facilisis scelerisque nulla. Praesent lobortis nisi ac leo laoreet, quis molestie ipsum porta. Suspendisse aliquet in velit eu ullamcorper. Maecenas
    auctor, mi ut viverra elementum, metus turpis commodo orci, eu commodo erat dolor malesuada arcu. Fusce condimentum augue</p>
  <center><b>Voila!! You have reached the bottom, already! :)</b>
  </center>
</div>

нет необходимости вычислять фактическую высоту содержимого; вы можете просто прокрутить вниз много:

$(function () {
  $('.messageScrollArea').scrollTop(1E10);
});

прокрутка с анимацией:

слоев:

<div class='messageScrollArea' style='height: 100px;overflow: auto;'>
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
</div>

в jQuery части:

jQuery(document).ready(function(){       
    var $t = $('.messageScrollArea');
    $t.animate({"scrollTop": $('.messageScrollArea')[0].scrollHeight}, "slow");
});

http://jsfiddle.net/3Wx3U/

//note: use of stop function to prevent animation build-ups if called repeatedly
//subtracting container height brings scrollTo position to container bottom
scrollUp = function() {
    $("#scroller").stop().animate({ scrollTop: 0 }, "slow");
}

scrollDown = function() {
    var scroller = $('#scroller');
    var height = scroller[0].scrollHeight - $(scroller).height();

    $(scroller).stop().animate({ scrollTop: height }, "slow");
}

$(function() {
  var wtf    = $('#scroll');
  var height = wtf[0].scrollHeight;
  wtf.scrollTop(height);
});
 #scroll {
   width: 200px;
   height: 300px;
   overflow-y: scroll;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scroll">
    <br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/> <center><b>Voila!! You have already reached the bottom :)<b></center>
</div>

сделать функцию jQuery более гибкой.

$.fn.scrollDown=function(){
    let el=$(this)
    el.scrollTop(el[0].scrollHeight)
}

$('div').scrollDown()

https://jsfiddle.net/Thielicious/82ar7db2/

jQuery простое решение, одна строка, не требуется внешний lib:

$("#myDivID").animate({ scrollTop: $('#myDivID')[0].scrollHeight }, 1000);

изменить 1000 на другое значение (это длительность анимации).

вот один пример:http://jsfiddle.net/CUUfb/1/