简体   繁体   English

始终将滚动条保持在底部

[英]Hold scroll bar always at the bottom

I have a div element and a simple style sheet for it : 我有一个div元素和一个简单的样式表:

CSS: CSS:

.container{
    width:200px;
    max-height:200px;
    border:1px solid red;
    overflow-y:scroll;
}

HTML: HTML:

<div class="container">
</div>

And i have a button for add contents to the div, as you know my div 's height grows then has an scroll bar. 我有一个用于向div添加内容的按钮,因为您知道我的div的高度会增加,然后有一个滚动条。 When i add new contents to the container, i want to show the last added item. 当我向容器中添加新内容时,我想显示最后添加的项目。 I try to use scrollTop() jQuery function with infinite value but it didn't work. 我尝试使用具有无限值的scrollTop() jQuery函数,但是它不起作用。 Any Idea? 任何想法?

The Fiddle 小提琴

Edit : Because of using max-height, the maximum value of height property is 200. So i can't use this approach : 编辑:由于使用max-height,height属性的最大值是200。所以我不能使用这种方法:

$(".container").scrollTop($(".container").heigth());

Now, i can do it like this: 现在,我可以这样做:

$(".container").scrollTop(10000);

And it's working, but i think it isn't good idea! 它正在工作,但是我认为这不是一个好主意!

Update 更新

Thanks to Nicole Van for the simple and great approach! 感谢Nicole Van的简单而出色的方法! I change my fiddle with her solution : The Updated Fiddle 我用她的解决方案来改变我的小提琴

How are you adding? 您要如何添加? appending or preppending? 追加还是前置?

I mean you could get the new height of your container and scrollTo your new height if appending or scrollTo 0 if preppending 我的意思是你可以让你的容器及的新高度scrollTo新的高度,如果追加或scrollTo 0,如果preppending

---EDIT this makes the trick: ---编辑这使窍门:

$(".add").click(function(){
    i++;
    var s ="<p>added value "+i+" ! </p>";
    $(".container").append(s);
    var heightContainer = $(".container").height();
    $(".container").scrollTop(heightContainer);
});

-----EDIT------- This makes it, it overpass allways its innerheight so it works, even its not accurate: -----编辑-------这样,它将始终超过其内部高度,因此可以正常工作,甚至不准确:

var i=0;
$(".add").click(function(){
    i++;
    var s ="<p>added value "+i+" ! </p>", heightContainer;
    $(".container").append(s);
    heightContainer = $(".container").height() * i;
    $(".container").scrollTop(heightContainer);
});

The ideal solution is that you know the height of the elemnts you are inserting so the heightContainer will be elemHeight * i 理想的解决方案是您知道要插入的元素的高度,因此heightContainer将为elemHeight * i

 function ScrollToBottom(){
     var d = document.getElementById("MyDiv");
     d.scrollTop = d.scrollHeight;
}

Take a look at some other jQuery solutions here: 在这里看看其他一些jQuery解决方案:

Scroll to bottom of div? 滚动到div的底部?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM