点击按钮,将元素滚动到顶部


onClick of Button, Scroll the element to top

我想在我的页面上添加" add COMMENT"按钮。onClick显示的是添加评论的表单。我希望表单在页面的顶部滚动,这样用户就不需要向下滚动来查看所有评论。

<script>function showDiv() {
            var div = document.getElementById('comdiv');
            var button = document.getElementById('button');
            if (div.style.display !== "none") {
                div.style.display = "none";
                button.value = "Add Comments";
            }
            else {
                button.value = "Hide Comments";
                div.style.display = "block";
            }
        }</script>`<input type="button" id="button" name="answerswer" value="Add Comments" onclick="showDiv()"  autofocus />
    <div id="comdiv"  style="display:none;" class="answerswer_list" >
        <form name="form" id="form" action="" method="post">
            <p class="h5">Comment</p>
            <textarea name="comment" id="comment" placeholder="Write Comment, Max: 140 characters" rows="4"  class="width-50" onblur="checkMe()" ></textarea>
            <span class="forms-desc">Comments should atleast have 20 character's</span><br/>
      <button type="submit" name="submit" id="submitbutton" class="btn btn-green btn-outline" disabled="disabled">Post Comment</button>
        </form></div>`

将此代码用于您的"script"标签

$("#按钮").click(函数(){

   $('html,body').animate({scrollTop: '0px'}, 1000);

});

在按钮add onclick="goTop() "

和定义

<script>
function goTop(){
formName.submit(); // formName = the name property of the form you are submitting
window.scrollTo(0, 0);
</script>
scrollIdIntoView("comment-1"); 
function scrollIdIntoView(id,speed) {
    if ($('#'+id).length) {
        $('html,body').animate({
            scrollTop : $('#'+id).offset().top - 30
        }, speed);
        $('#'+id).show().focus().click();
        return false;
    };
};

$('button').click(function() {
  $('html, body').animate({
    scrollTop: '0px'
  });
});
li {
  list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
  <li>comment1</li>
</ul>
<button>Comment</button>

你可以给div添加一个ID,并使用'scrollTop'属性。

请看下面的链接:

相似的问题