繁体   English   中英

页面加载后滚动到div

[英]Scroll to div after page load

如果要从url http://www.website.com/#pageload加载id='#pageload'我想使页面滚动到div id='#pageload'

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

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

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

您的代码中似乎有一些语法错误。 请注意,在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> 

如果要从url http://www.website.com/#pageload加载div id='#pageload'我想使页面滚动到div id='#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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM