Jquery在行动后重返顶峰

时间:2017-03-08 09:06:23

标签: jquery html

我正在使用jquery点击按钮跳转到我页面的另一部分。我使用了以下内容:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
        $(document).ready(function (){
            $("#bike").click(function (){

                location.href = "#scrolltohere"; 

            });

        });
    </script>

//这是我点击

的地方
<a href="/Bike" id="bike">Bikes</a>

//这是我要跳到

的部分
<div class="eshop-section section" id="scrolltohere">
<h2 style="font-family: 'Lato'; font-size: 40px;" >&nbsp &nbsp &nbsp&nbsp &nbspBikes</h2>

但问题是,它滚动并返回到页面顶部。

在这种情况下该怎么办?

5 个答案:

答案 0 :(得分:2)

您不需要绑定事件处理程序以导航到某个部分,正确使用href

  

URL片段是一个以哈希标记(#)开头的名称,它指定当前文档中的内部目标位置(HTML元素的ID)。

<a href="#scrolltohere">Bikes</a>

&#13;
&#13;
<a href="#scrolltohere">Bikes</a>
<div style="min-height:1200px;"></div>
<div id="scrolltohere">Lorem Ipsum</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用e.preventDefault来阻止锚点的默认操作,您可以使用动画来生成平滑的滚动动画。

$(document).ready(function() {
  $("#bike").click(function(e) {
    e.preventDefault();
    $('html, body').animate({
    scrollTop: $("#scrolltohere").offset().top
}, 2000);
  });
});

此外,您必须在每个;之后添加&nbsp,例如:&nbsp;

请参阅下面的演示工作片段:

&#13;
&#13;
$(document).ready(function() {
  $("#bike").click(function(e) {
    e.preventDefault();
    $('html, body').animate({
      scrollTop: $("#scrolltohere").offset().top
    }, 2000);
  });
});
&#13;
.divider{
  height: 500px;
  background: #F00;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/Bike" id="bike">Bikes</a>
<div class='divider'></div>
<div class="eshop-section section" id="scrolltohere">
<h2 style="font-family: 'Lato'; font-size: 40px;" >&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Bikes</h2>
&#13;
&#13;
&#13;

<强>更新

如果您要滚动到的元素位于其他页面上,则可以删除用于jQuery的{​​{1}}代码,只需更改click上的href即可到:

anchor

答案 2 :(得分:0)

使用Javascript:

$(document).ready(function() {
  $("#bike").click(function() {
    location.href = "#scrolltohere";
    return false; // Block page from navigating away to /Bike
  });
});

HTML:将您的div更改为<a name="scrolltohere"></a>

<a name="scrolltohere"></a>

答案 3 :(得分:0)

<a href="#scrolltohere" id="bike">Bikes</a> 

使用上述声明代替

<a href="/Bike" id="bike">Bikes</a>

答案 4 :(得分:0)

所以当您点击Bikes链接时它会触发$("#bike").click事件,您设置location.href="#scrolltohere"它将滚动到那里但在此之后,页面将转到{{ 1}}因为您为点击的链接URL/Bikes设置了href属性,所以每当加载新页面时,它都会始终排在最前面。
如果您放置<a href="/Bike" id="bike">Bikes</a>锚标记的默认行为将无效,则该页面将不会重定向到e.preventDefault()

如果您打算向下滚动到URL/Bikes div,请将scrolltohere属性设置为href 或者将<a href="#scrolltohere" id="bike">Bikes</a>放在e.preventDefault();点击事件中。

$("#bike").click
//$(document).ready(function() {
// $("#bike").click(function(e) {
//    e.preventDefault();
//    location.href = "#scrolltohere";    
//  });
//});
.section {
  margin-top: 5000px;
}

相关问题