ajax load content with anchor-link? live-handler?
hey guys, i'm loading a div from a subsite with ajax. this subsite has a link in it like this:
<a href="#someIDonHomepage">anchorlink</a>
My homepage where the ajax request is fired has this #someIDonHomepage div and i want my page to jump to that position.
However 开发者_Python百科since i'm loading the anchor with ajax this doesn't work.
any idea how i could solve that?
I wrote this animated scroll script with jquery that animates the jump when clicking on anchors.
/*Animated scroll for anchorlinks*/
var anchor = '',
pageOffset = '',
viewOffset = 30,
scrollPos = '';
$(function() {
$("a[href*='#']").each(function() {
$(this).addClass('anchorLink');
$(this).bind('click', function(e) {
e.preventDefault();
anchor = $(this).attr('href').split('#')[1];
pageOffset = $("a[name='#"+anchor+"']").offset();
scrollPos = pageOffset.top - viewOffset;
$('html, body').animate({scrollTop:scrollPos}, '500');
})
});
});
Any idea how i could solve that? thank you
jQuery Ajaxy has built in support for using ajax with hashes, as well as backwards support for traditional anchors - click the durian tab in the demo.
http://balupton.com/sandbox/jquery-ajaxy/demo/
You can use the LearningJquery approach or even using their plugin directly.
Example of their approach.
$(document).ready(function() {
var viewOffset = 30;
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
$('a[href*=#]').each(function() {
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
var $target = $(this.hash), target = this.hash;
if (target) {
var targetOffset = $target.offset().top - viewOffset;
$(this).click(function(event) {
event.preventDefault();
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
location.hash = target;
});
});
}
}
});
// use the first element that is "scrollable"
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
精彩评论