[英]Execute javascript function on anchor click, but the code must run on the page opened by that anchor
這可能嗎? 我需要單擊事件處理程序中的代碼,才能在該導航鏈接打開的新HTML頁面上執行。
我提出了一個小提琴,以更好地說明我想要實現的目標。 http://jsfiddle.net/hWEpL/4/
這是用於滾動的jQuery:
$.fn.scrollView = function () {
return this.each(function () {
$('html, body').animate({
scrollTop: $(this).offset().top
}, 1000);
});
}
$('#link-3').click(function (event) {
event.preventDefault();
$('.section-3').scrollView();
});
讓我們假設小提琴是主頁。 單擊第3節時,頁面滾動到第3節。
現在,假設我們在第二頁(關於),然后單擊第3節。 我想打開主頁,並將頁面滾動到第3節。
事實是,當打開主頁時,我不希望出現這種情況,只有在其他頁面上有人並單擊第3節時才需要它
您可以使用片段標識符 。 因此,例如在About頁面中,您將使用homepage.htm#section-3
鏈接到主頁,而在homepage.htm中,您將包含與所包含的代碼相同的內容,但是添加
var hash=location.hash
if(hash){
var el=$('.'+hash.substr(1))
if(el)
el.scrollView();
}
在onLoad中。 在這里,我們使用片段作為告訴頁面要轉到哪個元素的方法。
http://jsfiddle.net/hWEpL/5/這是更新的jsfiddle(使用來跟蹤模擬的哈希位置)
location.href="#section-3" //simulate named links
。 不要將此包含在您的代碼中
向前移動,也許從語義上講,如果禁用了javascript,則可以使用ID而不是類來使用片段的默認行為,但是您必須放置這段代碼以實際防止默認行為(並允許動畫發生)如https://stackoverflow.com/a/3659116/1480215中所述
setTimeout(function() {
if (location.hash) {
window.scrollTo(0, 0);
}
}, 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.