添加新内容时,保持DIV滚动到底

Keep DIV scrolled to bottom when new content is added

本文关键字:滚动 DIV 保持 新内容 添加      更新时间:2023-09-26

我有一个页面,在提交上一个表单时,它会将一个新表单添加到表单列表的底部,尽管我希望页面在达到一定高度时滚动,这样它就会滚动到顶部,隐藏最旧的表单,并在底部显示新表单。

新表单是使用AJAX创建的,这部分工作正常,只是滚动部分我无法工作。

<div id="no_image_audit_wrapper" class="content_wrapper">
<ul id="responds">
<?php
$sql = "SELECT * FROM add_delete_record";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
//get all records from add_delete_record table
while($row = mysqli_fetch_array($result))
{ ?>
  <li id="item_<? echo $row['id'];?>">
  <div class="del_wrapper"><a href="#" class="del_button" id="del-<? echo $row['id']; ?>">
  <img src="images/icon_del.gif" border="0" />
  </a></div>
  <? echo $row["content"].' - '.$row["dropdown"].'</li>';
 }
?>
</ul>
    <div class="form_style">
    <form id="test_form">
    <select id="test" name="test">
        <option value="test1">test1</option>
        <option value="test2">test2</option>
    </select>
    <textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea>
    <input type="button" class="FormSubmit" name="FormSubmit" id="FormSubmit" value="submit">
    </form>
    </div>
</div>

<script>
  $(document).ready(function(){
    var $cont = $('.content_wrapper');
    $cont[0].scrollTop = $cont[0].scrollHeight;
    $('.FormSubmit').keyup(function(e){
    if(e.keycode == 6){
        $cont.animate({ scrollTop: $cont[0].scrollHeight }, "slow");
        $(this).val('');
          }
     })
  }
</script>

使用下面的代码滚动到底部。您可以设置动画以缓慢滚动

Javascript

window.scrollTo(0,document.body.scrollHeight);

JQuery

$('html, body').animate({scrollTop:$(document).height()}, 'slow');

试试这样的

Your_newly_added_form.scrollIntoView(true);

或者你可以创建一个类似的函数

function scroll(elm){
elm.scrollIntoView(true);
}

并在ajax调用完成后调用该函数。

我通过添加对其进行排序

$("#test_form").get(0).scrollIntoView();

进入成功功能

success:function(response){
    $("#responds").append(response);
    $("#contentText").val(''); //empty text field on successful
    $("#test_form").get(0).scrollIntoView();
}