使用.animate()跳转到div

时间:2017-09-19 12:57:08

标签: javascript jquery html css

尝试让div在按键上跳转到另一个div。我读到使用animate scrollTop可以解决问题,但它似乎没有工作

    $("#search").keypress(function(event) {
        if (event.which == 13) {
        $("#search").animate({
            scrollTop: $("#results").offset().top}, "fast");
          var keyword = $("#search").val();
          $("#results").html(makeRequest);
          $("#search").val('');
        }
      }
   });

https://jsfiddle.net/4ymyLoLL/

2 个答案:

答案 0 :(得分:3)

问题是你必须为页面的主体设置动画,而不是div,如jsFiddle所示。

https://jsfiddle.net/4ymyLoLL/1/

$('html, body').animate({
  scrollTop: $("#results").offset().top
}, "fast");

编辑:提高代码可读性

答案 1 :(得分:0)

$('body,html').animate({ scrollTop: $("#results").offset().top }, 400);



$(function() {
  $("#search").on('keypress',function(event) {
    if (event.which == 13) {
    $('body,html').animate({ scrollTop: $("#results").offset().top }, 400);
      var keyword = $("#search").val();
      $("#results").html("test");
      $("#search").val('');
    }
  });
});

body, html {
  margin: 0 auto;
}

.container-fluid {
  padding:0px !important;
}

.right {
  background-color: #fcfdfe;
  width:100%;
  height:100vh;
}

.left {
  background-color: #eef1f9;
  width:100%;
  height:100vh;
}


#search {
  background-color: #fcfdfe;
  border: none;
  border-radius: 100px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: 0;
  padding:10px;
  width:350px;
  margin-right: -50%;
  transform: translate(-50%, -25%);
  display:inline-block;
}

#search:focus {
  outline: none;
}

#results {
  padding: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div class="wrapper">
    <div class="container-fluid">
      <div class="left">
        <input type="search" id="search" placeholder="Enter a keyword" class="keyword" />
      </div>
      <div class="right">
        <div id="results">
        </div>
      </div>
    </div>
  </div>
&#13;
&#13;
&#13;