jQuery jQuery从不同的页面滚动到ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9652944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery scroll to ID from different page
提问by Digital site
I was trying to use jQuery's page scroll inside some pages and could successfully make a smooth page scroll. The only problem I have now is when attempting to do that from different page. What I mean by that is if I click on a link in a page, it should load the new page and then scroll to the specific div element.
我试图在某些页面内使用 jQuery 的页面滚动,并且可以成功地进行平滑的页面滚动。我现在唯一的问题是尝试从不同页面执行此操作时。我的意思是如果我点击页面中的链接,它应该加载新页面,然后滚动到特定的 div 元素。
Here is the code I used to scrolling inside the page:
这是我用来在页面内滚动的代码:
var jump=function(e)
{
//prevent the "normal" behaviour which would be a "hard" jump
e.preventDefault();
//Get the target
var target = $(this).attr("href");
//perform animated scrolling
$('html,body').animate(
{
//get top-position of target-element and set it as scroll target
scrollTop: $(target).offset().top
//scrolldelay: 2 seconds
},2000,function()
{
//attach the hash (#jumptarget) to the pageurl
location.hash = target;
});
}
$(document).ready(function()
{
$('a[href*=#]').bind("click", jump);
return false;
});
I hope the idea is clear.
我希望这个想法很清楚。
Thanks
谢谢
Very important Note: This code I posted above works great inside the same page, but what I'm after is to click a link from one page and go to another one and then scroll to the target. I hope it is clear now. Thanks
非常重要的注意:我上面发布的这段代码在同一页面内效果很好,但我所追求的是从一个页面单击一个链接并转到另一个页面,然后滚动到目标。我希望现在清楚了。谢谢
回答by Petr Vostrel
You basically need to do this:
你基本上需要这样做:
- include the target hash into the link pointing to the other page (
href="other_page.html#section"
) - in your
ready
handler clear the hard jump scroll normally dictated by the hash and as soon as possible scroll the page back to the top and calljump()
- you'll need to do this asynchronously - in
jump()
if no event is given, makelocation.hash
the target - also this technique might not catch the jump in time, so you'll better hide the
html,body
right away and show it back once you scrolled it back to zero
- 将目标哈希包含在指向其他页面的链接中 (
href="other_page.html#section"
) - 在您的
ready
处理程序中清除通常由哈希决定的硬跳转滚动,并尽快将页面滚动回顶部并调用jump()
- 您需要异步执行此操作 - 在
jump()
如果没有给出事件,使location.hash
目标 - 此外,此技术可能无法及时捕捉到跳跃,因此您最好立即隐藏
html,body
并在将其滚动回零后将其显示回来
This is your code with the above added:
这是添加了上述内容的代码:
var jump=function(e)
{
if (e){
e.preventDefault();
var target = $(this).attr("href");
}else{
var target = location.hash;
}
$('html,body').animate(
{
scrollTop: $(target).offset().top
},2000,function()
{
location.hash = target;
});
}
$('html, body').hide();
$(document).ready(function()
{
$('a[href^=#]').bind("click", jump);
if (location.hash){
setTimeout(function(){
$('html, body').scrollTop(0).show();
jump();
}, 0);
}else{
$('html, body').show();
}
});
Verified working in Chrome/Safari, Firefox and Opera. Dunno about IE though.
经验证可在 Chrome/Safari、Firefox 和 Opera 中使用。虽然不知道 IE。
回答by Sarfraz
On the link put a hash:
在链接上放一个哈希:
<a href="otherpage.html#elementID">Jump</a>
And on other page, you can do:
在其他页面上,您可以执行以下操作:
$('html,body').animate({
scrollTop: $(window.location.hash).offset().top
});
On other page, you should have element with id set to elementID
to scroll to. Of course you can change the name of it.
在其他页面上,您应该将 id 设置为elementID
要滚动到的元素。当然,您可以更改它的名称。
回答by zanetu
Combining answers by Petr and Sarfraz, I arrive at the following.
结合 Petr 和 Sarfraz 的回答,我得出以下结论。
On page1.html:
在 page1.html 上:
<a href="page2.html#elementID">Jump</a>
On page2.html:
在 page2.html 上:
<script type="text/javascript">
$(document).ready(function() {
$('html, body').hide();
if (window.location.hash) {
setTimeout(function() {
$('html, body').scrollTop(0).show();
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top
}, 1000)
}, 0);
}
else {
$('html, body').show();
}
});
</script>
回答by Fresheyeball
I would like to recommend using the scrollTo plugin
我想推荐使用 scrollTo 插件
http://demos.flesler.com/jquery/scrollTo/
http://demos.flesler.com/jquery/scrollTo/
You can the set scrollto by jquery css selector.
您可以通过 jquery css 选择器设置 scrollto。
$('html,body').scrollTo( $(target), 800 );
I have had great luck with the accuracy of this plugin and its methods, where other methods of achieving the same effect like using .offset()
or .position()
have failed to be cross browser for me in the past. Not saying you can't use such methods, I'm sure there is a way to do it cross browser, I've just found scrollTo to be more reliable.
我对这个插件及其方法的准确性感到非常幸运,在过去,实现相同效果的其他方法,例如使用.offset()
或.position()
未能跨浏览器。并不是说您不能使用此类方法,我确定有一种方法可以跨浏览器执行此操作,我刚刚发现 scrollTo 更可靠。
回答by sg3s
I made a reusable plugin that can do this... I left the binding to events outside the plugin itself because I feel it is too intrusive for such a little helper....
我制作了一个可重复使用的插件,可以做到这一点......我把绑定到插件本身之外的事件留给了我,因为我觉得对于这样一个小帮手来说太麻烦了......
jQuery(function ($) {
/**
* This small plugin will scrollTo a target, smoothly
*
* First argument = time to scroll to the target
* Second argument = set the hash in the current url yes or no
*/
$.fn.smoothScroll = function(t, setHash) {
// Set time to t variable to if undefined 500 for 500ms transition
t = t || 500;
setHash = (typeof setHash == 'undefined') ? true : setHash;
// Return this as a proper jQuery plugin should
return this.each(function() {
$('html, body').animate({
scrollTop: $(this).offset().top
}, t);
// Lets set the hash to the current ID since if an event was prevented this doesn't get done
if (this.id && setHash) {
window.location.hash = this.id;
}
});
};
});
Now next, we can onload just do this, check for a hash and if its there try to use it directly as a selector for jQuery. Now I couldn't easily test this at the time but I made similar stuff for production sites not long ago, if this doesn't immediatly work let me know and I'll look into the solution I got there.
现在接下来,我们可以 onload 只是这样做,检查散列,如果它在那里尝试直接使用它作为 jQuery 的选择器。现在我当时无法轻松测试,但不久前我为生产站点制作了类似的东西,如果这不能立即起作用,请告诉我,我会研究我到那里的解决方案。
(script should be within an onload section)
(脚本应该在一个 onload 部分)
if (window.location.hash) {
window.scrollTo(0,0);
$(window.location.hash).smoothScroll();
}
Next we bind the plugin to onclick of anchors which only contain a hash in their href attribute.
接下来,我们将插件绑定到仅在其 href 属性中包含哈希值的锚点的 onclick。
(script should be within an onload section)
(脚本应该在一个 onload 部分)
$('a[href^="#"]').click(function(e) {
e.preventDefault();
$($(this).attr('href')).smoothScroll();
});
Since jQuery doesn't do anything if the match itself fails we have a nice fallback for when a target on a page can't be found yay \o/
因为如果匹配本身失败,jQuery 不会做任何事情,我们有一个很好的后备,当页面上的目标无法被找到 yay \o/
Update
更新
Alternative onclick handler to scroll to the top when theres only a hash:
当只有一个散列时,另一种 onclick 处理程序滚动到顶部:
$('a[href^="#"]').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
// In this case we have only a hash, so maybe we want to scroll to the top of the page?
if(href.length === 1) { href = 'body' }
$(href).smoothScroll();
});
Here is also a simple jsfiddle that demonstrates the scrolling within page, onload is a little hard to set up...
这里还有一个简单的 jsfiddle 演示页面内的滚动,onload 有点难以设置...
http://jsfiddle.net/sg3s/bZnWN/
http://jsfiddle.net/sg3s/bZnWN/
Update 2
更新 2
So you might get in trouble with the window already scrolling to the element onload. This fixes that: window.scrollTo(0,0);
it just scrolls the page to the left top. Added it to the code snippet above.
因此,您可能会遇到窗口已经滚动到 onload 元素的问题。这解决了这个问题:window.scrollTo(0,0);
它只是将页面滚动到左上角。将其添加到上面的代码片段中。
回答by sg3s
function scroll_down(){
$.noConflict();
jQuery(document).ready(function($) {
$('html, body').animate({
scrollTop : $("#bottom").offset().top
}, 1);
});
return false;
}
here "bottom" is the div tag id where you want to scroll to. For changing the animation effects, you can change the time from '1' to a different value
这里的“底部”是您要滚动到的 div 标签 ID。要更改动画效果,您可以将时间从“1”更改为不同的值
回答by John-Henry
I've written something that detects if the page contains the anchor that was clicked on, and if not, goes to the normal page, otherwise it scrolls to the specific section:
我写了一些东西来检测页面是否包含被点击的锚点,如果没有,则转到普通页面,否则滚动到特定部分:
$('a[href*=\#]').on('click',function(e) {
var target = this.hash;
var $target = $(target);
console.log(targetname);
var targetname = target.slice(1, target.length);
if(document.getElementById(targetname) != null) {
e.preventDefault();
}
$('html, body').stop().animate({
'scrollTop': $target.offset().top-120 //or the height of your fixed navigation
}, 900, 'swing', function () {
window.location.hash = target;
});
});