Howto: Jquery Scrollto Action after Pageload instead Click?

假装没事ソ 提交于 2019-12-11 17:26:15

问题


Figured this needed a better explanation:

I have a navigation with some links:

<a id="home" href="/">Home</a>
<a id="screenshots" class="scroll_to_screenshots" href="#">Screenshots</a>
<a id="ask" class="scroll_to_container" href="/ask">Support</a>

And I have a js file with the following:

$(document).ready(function() {
$(".scroll_to_screenshots").click(function() {$.scrollTo($("#screenshots").position().top+10, 300)});
$(".scroll_to_container").click(function() {$.scrollTo($("#container").position().top-10, 300)});
});

Now for the screenshots it works fine: it scrolls down to the screenshots id. However the second one needs to load a page first, then scroll. Obviously that does not work (it scrolls down briefly and then the page loading kicks in. Can I change that action to -load page first, -scroll down?

And then obviously I have another problem, when I am on .../ask the first link doesn't work anymore.


回答1:


simple

you should use in the page load function :

ScriptManager.RegisterStartupScript(this, GetType(), ToString(), "$.scrollTo($('#container').position().top-40, 300)", true);



回答2:


put this in contact page.

<script type="text/javascript">
  $(function(){
     $.scrollTo($("#container").position().top-40, 300);
  });
</script>



回答3:


So this does the trick. However if someone has a more refined, elegant answer I'm all ears.

// on the /example slug only
var fragment = 'example';

var url = window.location.href.split('/');

var last_item = url[url.length-2];
last_item = last_item.replace(/(\?|\#).*/, '');

if (last_item == fragment) {
    setTimeout(function() {$.scrollTo($("ul#posts").position().top, 300);}, 1000);



回答4:


Instead of using this:

$(document).ready(function(){
   // Your stuff here
});

Try using this:

$(window).load(function(){
   // Your stuff here
});

This will make the script wait until all elements on the page are loaded in before it scrolls.



来源:https://stackoverflow.com/questions/7498392/howto-jquery-scrollto-action-after-pageload-instead-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!