防止页面滚动到顶部 [英] Prevent page from scrolling to top
问题描述
我的jQuery Mobile和锚链接都有点问题。
I have a little problem with jQuery Mobile and anchor link's by url.
当页面加载时,jquery throw事件工作正常,但是jquery执行代码和将页面移至页面顶部。
*我的问题是没有在同一页面中链接锚点,是用网址链接另一个页面,例如: example_jquery.html #wopwop
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>
我在stackoverflow中写了一个补丁,看看帖子:
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。
对不起,我的英语很差
Thx. Sorry for my poor english
推荐答案
显示页面时jQuery Mobile的默认行为是在显示时滚动到顶部页面。 scroll的值始终为 0
并存储在 $ .mobile.defaultHomeScroll
。
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;
}
这将强制滚动到 wopwop
div在页面中的偏移量而不滚动到顶部然后再回到该div。
This will force scrolling to wopwop
div's offset in page without scrolling to top and then back to that div.
这篇关于防止页面滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!