我希望在双方附加/提交新文本后将滚动条移动到底部。即滚动条应该在发送文本的用户一侧移动到底部,并且滚动条应该在接收文本的用户一侧移动。
<?php
session_start();
?>
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link href="style.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
<script src="jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<br />
<br />
<br />
<div class="col-lg-6 col-md-6">
<div class="table-responsive">
<h3 align="center">You Are : <?php echo $_SESSION['name']; ?></h3><br />
<div id="live_data"></div>
</div>
</div>
<div class="col-lg-6 col-md-6">
<div class="chatbox">
<div id="messages"></div>
<div class="area" style="display:none">
<div class="chat-form">
<textarea id="text" name="text"></textarea>
<button type="submit" id="sub" name="sub">Send</button>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var currentID = null;
var chatTimer = null;
var scrolled;
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
//fetch_chat();
}
});
}
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$("#messages").show();
$('#messages').html(data);
$("div.area").show();
if(!scrolled){
$("#messages").animate({ scrollTop: $(document).height() }, "fast");
scrolled=true;
}
}
});
}
$(document).ready(function() {
$("#messages").on('scroll',function(){
scrolled=true;
});
fetch_data();
$(document).on('click', '.first_name', function() {
scrolled=false;
currentID = $(this).data("id1");
fetch_chat();
});
setInterval(function() {
fetch_chat();
}, 500);
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: currentID,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
$("#messages").animate({ scrollTop: $(document).height() }, "fast");
});
});
});
</script>
</body>
</html>
问题在于,无论何时添加新文本,文本都会在侧面向下到底,并且滚动br保持在其位置(但应沿新文本移动)。