最近我尝试更频繁地使用jQuery,现在我遇到了一些问题,希望您能帮助我解决。
我的网页中包含一些锚点(假设该锚点位于页面中间),在“onload”事件上,我希望页面从特定的锚点位置开始,即页面将自动“滚动”到特定位置。
这是我以前的解决方案(这很丑陋,因为它会向我的URL添加 #i)。
window.onload = window.location.hash = 'i';
无论如何,你能告诉我如何使用jQuery实现吗?
注意:我不希望用户在跳转到这个位置时感受到任何幻灯片或特效。
最近我尝试更频繁地使用jQuery,现在我遇到了一些问题,希望您能帮助我解决。
我的网页中包含一些锚点(假设该锚点位于页面中间),在“onload”事件上,我希望页面从特定的锚点位置开始,即页面将自动“滚动”到特定位置。
这是我以前的解决方案(这很丑陋,因为它会向我的URL添加 #i)。
window.onload = window.location.hash = 'i';
无论如何,你能告诉我如何使用jQuery实现吗?
注意:我不希望用户在跳转到这个位置时感受到任何幻灯片或特效。
使用以下简单示例
function scrollToElement(ele) {
$(window).scrollTop(ele.offset().top).scrollLeft(ele.offset().left);
}
这里的ele
是你的元素(jQuery)。例如:scrollToElement($('#myid'));
不需要使用jQuery,因为这是本地的JavaScript功能
element.scrollIntoView()
scrollIntoView
有广泛的支持(只有Firefox支持选项参数)。 - graham mendick我已经尝试了几个小时,最简单的方法来阻止浏览器跳转到锚点而不是滚动到它的位置是:使用另一个锚点(一个在您网站上未使用的id)。因此,您可以将链接从“http://#YourActualID”更改为“http://#NoIDonYourSite”。这样,浏览器就不会再跳转了。
然后,只需检查是否设置了锚点(使用下面提供的脚本,该脚本摘自其他线程!),并设置要滚动到的实际id。
$(document).ready(function(){
$(window).load(function(){
// Remove the # from the hash, as different browsers may or may not include it
var hash = location.hash.replace('#','');
if(hash != ''){
// Clear the hash in the URL
// location.hash = ''; // delete front "//" if you want to change the address bar
$('html, body').animate({ scrollTop: $('#YourIDtoScrollTo').offset().top}, 1000);
}
});
});
请查看https://lightningsoul.com/media/article/coding/30/YOUTUBE-SOCKREAD-SCRIPT-FOR-MIRC#content,以查看一个可行的示例。
#YourIDtoScrollTo
更改为'+hash+'
,以便滚动到我的网站提供的任何动态哈希和用户导航到... - Hudson Santos$(document).ready(function()
和 $(window).load(function()
? - Chuck Le Butti achieve it like this..
if(location.pathname == '/registration')
{
$('html, body').animate({ scrollTop: $('#registration').offset().top - 40}, 1000);
}
/* START --- scroll till anchor */
(function($) {
$.fn.goTo = function() {
var top_menu_height=$('#div_menu_header').height() + 5 ;
//alert ( 'top_menu_height is:' + top_menu_height );
$('html, body').animate({
scrollTop: (-1)*top_menu_height + $(this).offset().top + 'px'
}, 500);
return this; // for chaining...
}
})(jQuery);
$(document).ready(function(){
var url = document.URL, idx = url.indexOf("#") ;
var hash = idx != -1 ? url.substring(idx+1) : "";
$(window).load(function(){
// Remove the # from the hash, as different browsers may or may not include it
var anchor_to_scroll_to = location.hash.replace('#','');
if ( anchor_to_scroll_to != '' ) {
anchor_to_scroll_to = '#' + anchor_to_scroll_to ;
$(anchor_to_scroll_to).goTo();
}
});
});
/* STOP --- scroll till anchror */
只需使用scrollTo插件
$("document").ready(function(){
$(window).scrollTo("#div")
})
#[要滚动到的div的id]
附加到您的页面URL即可。例如,如果我想滚动到此stackoverflow问题的版权部分,则URL将从原来的...变为...https://dev59.com/CGkw5IYBdhLWcg3wn8CO
到
https://dev59.com/CGkw5IYBdhLWcg3wn8CO#copyright
#copyright
。