如何在php JS中防止div重载中的scrollHeight?

时间:2018-04-04 00:11:13

标签: javascript html

我正在尝试进行实时聊天,我正在使用这个JS代码:



$(document).ready(function() {

	// 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('');

				}).fail(function(err) {

				//alert HTTP server error
				alert(err.statusText);
				});
			}
	});

	//toggle hide/show shout box
	$(".close_btn").click(function (e) {
		//get CSS display state of .toggle_chat element
		var toggleState = $('.toggle_chat').css('display');

		//toggle show/hide chat box
		$('.toggle_chat').slideToggle();

		//use toggleState var to change close/open icon image
		if(toggleState == 'block')
		{
			$(".header div").attr('class', 'open_btn');
		}else{
			$(".header div").attr('class', 'close_btn');
		}


	});
});




来源:https://www.sanwebe.com/assets/chat-shout-box/

我的问题是,因为我正在使用 var scrolltoh = $('.message_box')[0].scrollHeight; $('.message_box').scrollTop(scrolltoh);,每次重页加载时,它始终会滚动到底部。

我想要做的是,当有人发送新聊天时,它只会滚动到底部。就像在facebook中一样。

提前致谢。

1 个答案:

答案 0 :(得分:1)

请试试这个:

	// 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; //try to replace this in other place just play with the code
		//$('.message_box').scrollTop(scrolltoh);
	 });
	}, 1000);

希望至少有一点帮助。

加上这段代码:

function chatFunc(){
	setTimeout(function() {
	  //your code to be executed after 1 second
		var scrolltoh = $('.message_box')[0].scrollHeight;
		$('.message_box').scrollTop(scrolltoh);
	}, 1000);
}
window.onload = chatFunc;