更新时间:2023-12-05 09:13:28
首先,让我们摆脱无效的ID,他们不能以数字开头,直到HTML5,我倒是preFIX您的ID与像 ID =NAV1
。
这部分是清理,你能为滚动操作是这样的:
$(A)。生活(点击,函数(事件){
VAR哈希= this.hash;
$(#内容)。载荷(this.href,函数(){
document.location.hash =散列;
});
event.stopImmediatePropagation();
。事件preventDefault();
});
这会运行一次的内容加载,所以有一些滚动到。这种做法立刻去那里,所以要制作动画...这是很容易的,以及:
$(A)。生活(点击,函数(事件){
VAR哈希= this.hash;
$(#内容)。载荷(this.href,函数(){
VAR ST = $(散).scrollTop();
$('HTML,身体)动画({scrollTop的:ST},200); // 200毫秒时间
});
event.stopImmediatePropagation();
。事件preventDefault();
});
我们要存储 this.hash
作为一个变量,因为该回调里面,这
将参照#内容
元素,而不是我们点击了锚。
I'm building a website to organize comics collections.
So you have on the left a list of yours comics and if you click on one of them, the page with the details about that comic is loaded on the right with AJAX with the jQuery load()
function.
I don't have a page for every comic but for every serie (one for all the "Walking dead", one for all the "Spiderman"....) so on every page that can be a lot of different comics.
However when clicking on a specific comic I not only want to load the correct page but also to go at the correct position in this page.
I have anchors in every page (#i12,#i13 with a unique number each time).
How can I, after the content is loaded using AJAX, go to the correct anchor ? I tried to dynamically modify the page URL (adding a #i12 at the end) but without success.
I was using document.location.hash
, bad idea ?
#i120
Main page :
<div id="list">
<a href="test.php#i120">Go to num 120</a>
</div>
<div id="content">
</div>
Javascript :
$("a").live('click',function (event)
{
$("#Content").load(this.href);
event.stopImmediatePropagation();
event.preventDefault();
});
Page Test.php :
<div id="i1">Text1</div>
...
...
<div id="i120">Text120</div>
First, let's get rid of invalid IDs, they can't start with a number until HTML5, I'd prefix your IDs with something like id="nav1"
.
That part is cleanup, what you can do for the scrolling is this:
$("a").live('click', function(event) {
var hash = this.hash;
$("#Content").load(this.href, function() {
document.location.hash = hash;
});
event.stopImmediatePropagation();
event.preventDefault();
});
That'll run once the content is loaded, so there's something to scroll to. That approach instantly goes there, so to animate it...that's easy enough as well:
$("a").live('click', function(event) {
var hash = this.hash;
$("#Content").load(this.href, function() {
var st = $(hash).scrollTop();
$('html, body').animate({ scrollTop: st }, 200); //200ms duration
});
event.stopImmediatePropagation();
event.preventDefault();
});
We're storing this.hash
as a variable because inside that callback, this
will refer to the #Content
element, not the anchor we clicked on.