我有一个div,当你点击它时,它假设输出另一个可滚动的div,并滚动到该div的底部。现在,它正在输出可滚动的div,但它不会滚动到底部。我做错了什么?
test1.php
#output {
border: 1px solid black;
width: 100%;
}
<div id = "output" onclick = "scrollToBottom()"> Click me </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function scrollToBottom() {
$.ajax({
type: "POST",
url: "test2.php",
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById("output").innerHTML = data;
} //end of success:function(data)
}); //end of $.ajax
var objDiv = document.getElementById("messageBox");
objDiv.scrollTop = objDiv.scrollHeight;
} //end of scrollToBottom()
</script>
test2.php
<?php
echo "
<style>
#messageBox {
border: 3px solid green;
overflow-y: scroll;
height: 400px;
padding: 1%;
}
</style>
<div id = 'messageBox'>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
</div>
"
?>
答案 0 :(得分:0)
如果我理解正确,您想要滚动到点击创建的div的底部。如果是这样,问题很可能是
var objDiv = document.getElementById("messageBox");
objDiv.scrollTop = objDiv.scrollHeight;
在成功函数之前触发。所以试试:
success:function(data) {
document.getElementById("output").innerHTML = data;
var objDiv = document.getElementById("messageBox");
objDiv.scrollTop = objDiv.scrollHeight;
} //end of success:function(data)e