我在我的网站上使用JQuery 1.7.2和JQuery UI 1.10.3设置了一个Tab小部件。
我已经编写了一个JavaScript,它解析URL的哈希部分,这样我就可以打开一个选项卡,将内容加载到div中,并滚动到一个命名的锚点。
我可以打开选项卡,加载内容,但是,滚动到锚点确实很痛苦。
如果我在滚动到锚点之前触发警报(迫使你点击"确定"),我可以让它工作,但如果我禁用警报(我想禁用),它就不工作了。
我猜这与等待函数首先完成处理有关?但我对JavaScript非常缺乏经验,所以我非常感谢任何人能提供的帮助。
URL example: http://www.mysite.com/abc.html#tab=tab-3&#srv=includes/xyz&#anc=myanchor
我的JavaScript如下:
$(document).ready(function () {
var parts = location.hash;
parts = parts.split('&'); // Hash parts of URL.
for (var i = 0; i < parts.length; i++) // Loop to separate variables.
{
if (parts[i].substr(1, 4).toUpperCase() == "TAB=") {
var tab = parts[i].substr(5).split("-").pop() - 1
} // Tab no. part from tab name.
if (parts[i].substr(1, 4).toUpperCase() == "SRV=") {
var srv = parts[i].substr(5)
} // Path to content to load.
if (parts[i].substr(1, 4).toUpperCase() == "ANC=") {
var anc = parts[i].substr(5)
} // Named anchor to locate.
};
// Tab found in URL so we'll check it exists and open it.
if (tab == -1) // Tab not found?
{
tab = 0 // Default to 1st tab if not.
};
$("#tabs").tabs("option", "active", tab); // Select the tab.
// Load content if provided in URL.
var href = $('.list li a').each(function () {
var href = $(this).attr('href');
if (srv == href.substr(0, href.length - 5)) {
var toLoad = srv + '.html .maint_content';
$('.maint_content').load(toLoad)
}
});
// Load content when selected from list.
$('.list li a').click(function () {
var toLoad = $(this).attr('href') + ' .maint_content';
$('.maint_content').fadeOut('normal', loadContent);
$('#load').remove();
$('.maint_content').fadeIn('normal', loadContent);
$('#load').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0, $(this).attr('href').length - 5);
function loadContent() {
$('.maint_content').load(toLoad, '', showNewContent());
}
function showNewContent() {
$('.maint_content').show('normal', hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
// Scroll to locate anchor.
//alert(anc);
$('html, body').animate({
'scrollTop': $('#' + anc).offset().top
}, 1000);
});
感谢
我假设您要跳转到的锚点在加载的内容中?
如果是这样,只需在ajax调用中添加一个回调,然后跳到那里:
$('.maint_content').load(toLoad,'',showNewContent()).done(function () {
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
});
您正在调整div的内容。这意味着它是异步加载的。因此,animate函数是在内容加载完成之前调用的,而您要查找的锚点还不在那里。
为了在加载完成时激发动画,可以将函数传递给.load()
$('.maint_content').load(toLoad,'',showNewContent());
所以你已经准备好了:showNewContent
在加载完成时被激发。所以你所要做的就是将动画线移动到该函数的末尾。
function showNewContent()
{
$('.maint_content').show('normal',hideLoader());
$('html, body').animate({'scrollTop': $('#'+anc).offset().top}, 1000);
}