Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

javascript - Prevent page from scrolling to top

I have a little problem with jQuery Mobile and anchor link's by url.

When page is load, after jquery throw event's work fine, but then jquery execute code and move page to top of page. *my problem is not linking anchor in same page, is link another page with anchor with url, for example: example_jquery.html#wopwop

I write a little example for see isn't work (you can test in any browser):

<html>
  <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css">
  </head>
  <body>
    <div data-role="page">
        <h1>wopwop</h1>
        <br/><br/><br/><br/><br/><br/><br/><br/><br/>
        <br/><br/><br/><br/><br/><br/><br/><br/><br/>
        <br/><br/><br/><br/><br/><br/><br/><br/><br/>
        <a id="wopwop"></a>
        <h1>wopwop</h1>
    </div>
  </body>

I write a patch looking post's in stackoverflow:

<script type="text/javascript">
  setTimeout(function(){
    if(location.hash  == "#wopwop"){
      $.mobile.silentScroll($('#wopwop').get(0).offsetTop);
    }
  }, 700);
</script>

But i don't think is solution, do you know how to make this work?.

Thx. Sorry for my poor english

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The default behavior of jQuery Mobile when showing pages is to scroll to top upon showing a page. The value of scroll is always 0 and stored in $.mobile.defaultHomeScroll.

You need to override this value on any page event but before page is totally shown and transition is done.

if (location.hash == "#wopwop") { 
  $.mobile.defaultHomeScroll = $('#wopwop').offset().top; 
}

This will force scrolling to wopwop div's offset in page without scrolling to top and then back to that div.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...