页面加载后滚动到div

时间:2016-12-18 08:26:40

标签: javascript jquery html

我想让我的页面滚动到div id='#pageload' 如果它是从网址http://www.website.com/#pageload

加载的

我使用了以下代码,但所有页面都重定向到http://www.website.com/#pageload

if(document.location ="/#pageload") {
    $('html, body').animate({
        scrollTop: $('#pageload').offset().top
    }, 'slow');
}

我该如何解决?非常感谢你。

2 个答案:

答案 0 :(得分:0)

您的代码中似乎存在一些语法错误。请注意,在if()中使用了一个等号(赋值符号),当您应该使用两个或三个(断言符号)时。查看代码段示例。



//you can get rid off that part
document.location.hash="#d";  //set url /#d dynamically
document.body.scrollTop = "0px";  //set scroll to 0
//you can get rid off that part

if(document.location.hash === "#d"){
 
        $('body').animate({
                scrollTop: $('#d').offset().top
        }, 'slow');
      }

.cont{
  width: 200px;
  height:500px;
  margin:10px;
  background-color:#fce4ec;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="cont" id="a">a</div>
<div class="cont" id="b">b</div>
<div class="cont" id="c">c</div>
<div class="cont" id="d">d</div>
<div class="cont" id="e">e</div>
<div class="cont" id="f">f</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

  

如果已加载,我想让我的页面滚动到div id='#pageload'   来自网址http://www.website.com/#pageload

这里的关键考虑因素是你需要使用与你希望新加载的窗口向下滚动到的元素的id 不同的哈希片段。

如果哈希片段与元素id相同,则窗口在加载时会自动将该元素定位在视口顶部...然后窗口无处可去滚动到,因此没有动画。

在下面的示例中,

  • 哈希片段是#topageload
  • 元素id#pageload

工作示例:

$(document).ready(function(){

    // The line below (and the second condition involving winLocHash are included just so this example works
    var winLocHash = '#toppageload';

    if ((window.location.hash === '#topageload') || (winLocHash === '#toppageload')) {
        $('html, body').animate({scrollTop: $("#pageload").offset().top}, 3000);
    }

});
body {
    background-color: rgb(255,255,0);
}

div {
    width: 100px;
    height: 100px;
    margin: 24px;
}

div:nth-of-type(odd) {
    background-color: rgb(255,0,0);
}

div:nth-of-type(even) {
    background-color: rgb(0,0,255);
}

#pageload {
    color: rgb(255,255,255);
    line-height: 100px;
    font-weight: bold; 
    text-align: center;
    background-color: rgb(0,127,0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

<div id="pageload">#Pageload</div>

<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

相关问题