2017-09-17 113 views
1

我有一个聊天框,人们可以在其中添加自己的消息,但我的问题是,添加新消息时,它不会向下滚动以显示新消息。 我通过使用此代码自动向下滚动,但在用户滚动时停止

固定这个
$('.panel-body').scrollTop($('.panel-body').height()*$('.panel-body').height()); 

(面板体是类我滚动的div)

但这样做的问题是,如果用户想要上翻在以前的消息,他否则她将被迫退到底部。当用户滚动时停止“自动滚动”的最好方法是什么,但是当用户向下滚动或者只是加载页面时,会再次启动。

function addMsg(is_admin, name, mes, time) { 

    var newDiv = document.createElement("div"); 
    newDiv.className = "row"; 
    var p = document.createElement("p"); 
    p.className = "text-muted name"; 
    var p2 = document.createElement("p"); 
    var text = document.getElementById("start"); 
    var hr = document.createElement("hr"); 
    var times = document.createElement("p") 
    text.appendChild(newDiv); 
    newDiv.appendChild(p); 
    p.innerHTML = name + ":"; 
    newDiv.appendChild(p2); 
    newDiv.appendChild(times) 
    times.className = "time"; 



    if (is_admin) { 
     p.style = "color: red;"; 
     p2.innerHTML = mes; 
     times.innerHTML = "time: " + time; 


    } else { 


     p2.innerHTML = mes; 
     times.innerHTML = time; 

    } 
    newDiv.appendChild(hr); 

这是我已经创建

+0

我认为这个帖子可能会感兴趣https://stackoverflow.com/questions/33639197/prevent-all-scrolling-until-a-function-触发器 –

+0

@MohamedChaawa从我看到的可以防止所有滚动 – ThatPurpleGuy

回答

1

这里有一个快速的尝试我扔在一起我ADDMSG功能。

从其scrollHeight(JS)减去元素的height()(jQuery的),并进行比较,为用户的scrollTop(jQuery的滚动位置),我们可以判断,如果我们在新的消息之前,目前在滚动容器的底部是出现。

如果我们在最下面,那么通过设置新的scrollTop来保持用户在那里。否则,不要改变任何东西。希望这可以帮助!

现场演示:

function newMsg() { 
 
    // FOR DEMO (naming each message) 
 
    var count = $('.msg').length; 
 

 
    // shouldScroll will be true if we're at the bottom of the 
 
    // scrollable container before the new message appears 
 
    var $panel = $('.panel-body'); 
 
    var shouldScroll = $panel[0].scrollHeight - $panel.height() <= $panel.scrollTop(); 
 

 
    // this is where you append a new message to the container 
 
    $panel.append('<div class="msg">Message ' + count + '</div>'); 
 

 
    // if we were at the bottom before the new message, 
 
    // then scroll to the new bottom of the container 
 
    if (shouldScroll) { 
 
    $panel.scrollTop($panel[0].scrollHeight); 
 
    } 
 
} 
 

 
// FOR DEMO (new message every .5 seconds) 
 
setInterval(newMsg, 500);
.panel-body { 
 
    border: 1px solid #000; 
 
    overflow: auto; 
 
    width: 200px; 
 
    height: 200px; 
 
} 
 

 
.msg { 
 
    border-bottom: 1px solid #ccc; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="panel-body"></div>

+0

我已经有一个addmsg函数,我应该把它放在哪里,使它工作? @JonUleis – ThatPurpleGuy

+0

@ThatPurpleGuy您没有向我们展示您的代码,因此无法回答 - 但这是为了帮助您了解如何在最小和功能性示例中实现您所要求的内容。您是否无法理解任何代码并对其进行修改? –

+0

哦,我以为我加了它。我的坏现在添加。另外我的问题是你通过多次重复功能,我必须这样做才能在我的情况下工作。对不起,我比java更熟悉java,我正在学习。 – ThatPurpleGuy