简体   繁体   English

根据滚动条位置保持div的滚动位置

[英]Maintain scroll position for a div based on scroll bar position

I've got my code written here . 我在这里写了我的代码。

setInterval(
    function (data){
        var alreadyScrolled = $("#smallBox").height() >= $("#smallBox").get()[0].scrollHeight;


        $("#smallBox").append(data + "<br />");
        if (alreadyScrolled) {
            $("#smallBox").scrollTop($("#smallBox").heightoffsetHeight)
        }
    },
    1000, 
    Date()
);


<div id="largeBox">
    <div id="smallBox">
    </div>
    <input />
</div>

What I'm trying to do is, detect if the scroll bar is at the bottom of the window, and if it is, append the new data into the div, then scroll back down to the bottom. 我要做的是,检测滚动条是否位于窗口的底部,如果是,则将新数据附加到div中,然后向下滚动到底部。 In the event that the scroll isn't already at the bottom, do nothing. 如果滚动不在底部,则不执行任何操作。

I'm not sure which parts of either the DOM or jquery API I can use to accomplish this, I've been trying multiple things and am somewhat stuck here, nothing seems to give me a value in terms of where the scroll bar is, and how much I can can scroll. 我不确定我可以使用DOM或jquery API的哪些部分来实现这一点,我一直在尝试多种方法并且有点卡在这里,似乎没有什么能给我一个关于滚动条位置的值,我可以滚动多少。 A percent value would be awesome if I could just get that. 如果我能得到它,那么百分之一的价值就会很棒。

I don't want to use any libraries outside of jQuery, this means no plugins either. 我不想在jQuery之外使用任何库,这意味着也没有插件。

I'm looking to get the same behavior we see in the SO chat rooms, except that it seems to be using the ScrollTo plugin to accomplish what it does. 我希望得到我们在SO聊天室中看到的相同行为,除了它似乎使用ScrollTo插件来完成它的功能。

Update. 更新。

I can't just use .height() and .scrollTop, they don't match up. 我不能只使用.height()和.scrollTop,它们不匹配。

See this: http://jsfiddle.net/qSx3M/6/ 见: http//jsfiddle.net/qSx3M/6/

I think this is what you're after? 我想这就是你要追求的?

http://jsfiddle.net/qSx3M/7/ http://jsfiddle.net/qSx3M/7/

Code: 码:

var alreadyScrolled = $("#smallBox")[0].scrollTop + $("#smallBox").height() == $("#smallBox")[0].scrollHeight;

Took your code and made small modifications. 拿走你的代码并进行小的修改。 Can't say if it is good code but it works 不能说它是否是好的代码,但它的工作原理

setInterval(
    function (data){
        var alreadyScrolled = $("#smallBox").height() + $("#smallBox").get()[0].scrollTop >= $("#smallBox").get()[0].scrollHeight;

        console.log(alreadyScrolled);

        $("#smallBox").append(data + "<br />");
        if (alreadyScrolled) {
            $("#smallBox").get()[0].scrollTop = $("#smallBox").get()[0].scrollHeight;
        }
    },
    1000, 
    Date()
);

普通的旧javascript滚动值:

var scrollVal = myDivElem.scrollTop;

Try this 尝试这个

var $this;
  $('#container').scroll(function(){
    $this = $(this);
    if ($this.scrollTop() > $this.height()){
       //Do something here
    }
});

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

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