0

我从http://www.saaraan.com/2013/04/creating-shout-box-facebook-style添加了这个喊话框, 可以在这里看到它的现场演示http://www.saaraan.com/2013/ 04/创建-喊话框-facebook-style

除了滑块本身,我的一切都正常工作。每次我尝试向上滚动时,它都会自动向下滚动。它不会停留在向上的位置。我认为问题就在这里。

// load messages every 1000 milliseconds from server.
load_data = {'fetch':1};
window.setInterval(function(){
$.post('shout.php', load_data,  function(data) {
$('.message_box').html(data);
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
});
}, 1000);

//method to trigger when user hits enter key
$("#shout_message").keypress(function(evt) {
if(evt.which == 13) {
var iusername = $('#shout_username').val();
var imessage = $('#shout_message').val();
post_data = {'username':iusername, 'message':imessage};

//send data to "shout.php" using jQuery $.post()
$.post('shout.php', post_data, function(data) {

//append data into messagebox with jQuery fade    effect!
$(data).hide().appendTo('.message_box').fadeIn();

//keep scrolled to bottom of chat!
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);

//reset value of message box
$('#shout_message').val('');

更具体地说在这里

var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);

和这里

//keep scrolled to bottom of chat!
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);

我已将 0 更改为 1 和其他数字,它修复了滚动以正常工作,但它不显示最新的喊叫,它会显示喊叫 25,这是删除前看到的最后一个喊叫。我不确定这是否有意义,但任何帮助都会很棒。

顶部的第一个链接显示整个代码,第二个链接显示示例

4

1 回答 1

0

试试这个代码,我没有测试过。我希望它会奏效。

window.setInterval(function() {
  $.post( 'shout.php', load_data, function( data ) {
    var old_data  = $(".message_box").html();
    if ( old_data != data ) {
      $(".message_box").html( data );

          // get scrollHeight
      var scrollHeight  = $(".message_box").get(0).scrollHeight,
          // get current scroll position
          scrollTop     = $(".message_box").scrollTop(),
          // calculate current scroll percentage
          percentage    = Math.round( ( 100 / scrollHeight ) * scrollTop );;

      // make sure user is not scrolled to top
      if ( percentage > 80 ) {
        $(".message_box").scrollTop( scrollTop );
      }
    }
  });
}, 1000);
于 2013-08-23T05:12:23.540 回答