简体   繁体   English

滚动到div的底部不起作用

[英]scroll to bottom of the div doesn't work

function ereja(){
  var newscrollHeight2 = $("#messages")[0].scrollHeight;
  return newscrollHeight2;
}

var newscrollHeight = ereja();
var oldscrollHeight = $("#messages")[0].scrollHeight;

function merrmesazhet(){
  $('#messages').load(
    "nxirr_mesazhet.php?room=<?php echo urlencode($dhoma24); ?>"
  );     
  setTimeout(ereja, 1000);
  if( newscrollHeight != oldscrollHeight ){ 
    $("#messages").scrollTop($("#messages")[0].scrollHeight); 
  }
}

What's wrong with this code? 此代码有什么问题? Why it doesn't work? 为什么不起作用? I am trying to scroll to bottom of the div when a user writtes a new message. 当用户编写新消息时,我试图滚动到div的底部。 Any idea? 任何想法?

Assuming you are actually calling merrmesazhet() and that you are testing on IE>=8 as lower versions don't support scrollHeight . 假设您实际上在调用merrmesazhet() ,并且您正在IE>=8上进行测试,因为较低的版本不支持scrollHeight Then your main issue is the use of setTimeout which is essentially calling ereja every second and doing nothing . 然后,您的主要问题是setTimeout的使用,它实际上ereja每秒调用一次ereja什么也不做。

Indeed you do not even need the JS timer - you are using jQuery which supports a callback in it's load function (which executes once on a successful load rather than repeatedly). 实际上,您甚至不需要JS计时器-您正在使用jQuery,它的load函数支持回调(该函数在成功加载后执行一次 ,而不是重复执行)。 Your if-statement in it's current form will always evaluate to false as it isn't within the function executed on the timer anyway. 当前形式的if语句将始终评估为false,因为它无论如何都不在计时器上执行的函数之内。

Something like this may work for you: 这样的事情可能适合您:

var oldscrollHeight = $("#messages")[0].scrollHeight;

function merrmesazhet(){
    $('#messages').load(
        'nxirr_mesazhet.php?room=<?php echo urlencode($dhoma24); ?>',
        function(){
            var newscrollHeight = $("#messages")[0].scrollHeight;
            if( newscrollHeight != oldscrollHeight ){
                $("#messages").scrollTop($("#messages")[0].scrollHeight);
            }
        }
    );
}

jsFiddle jsFiddle

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

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