[英]Hash location with offset
我在單頁設計上導航時遇到了一些麻煩。 以下是我的代碼。 代碼在主頁上正常工作。
固定標題不會與節部分重疊,效果很好。 但是,當我在網站的單個頁面上,並點擊鏈接到主頁上的部分的菜單項,如<a href="index.html#video"></a>
,滾動動畫將動畫顯示部分,但隨后固定的標題重疊該部分,當你等待3秒時,它將回到正確的位置。
我認為動畫將執行2次,但如果這是問題,我現在不會。 此外,我想知道如何編碼,當用戶刷新頁面時,它將返回到瀏覽器窗口的頂部。
JS小提琴:
您可以通過攔截onhashchange
事件並調整window
的偏移量來完成此操作:
(function($){
if ( "onhashchange" in window ) {
var hashHandler = function(){
var hash = window.location.hash.substring( 1 );
if ( !hash )
return;
var offset = 50;
var sel = '[id="' + hash + '"], a[name="' + hash + '"]';
var currentOffset = $( sel ).offset().top;
$( window ).scrollTop( currentOffset + offset );
};
window.addEventListener("hashchange", hashHandler, false);
window.addEventListener("load", hashHandler, false);
}
})(window.jQuery);
您的問題是動畫的完整處理程序。 你做這個:
window.location.hash = id;
此方法將滾動條移動到id為“id”的對象,但當然,這會忽略用於計算的偏移量(標題的高度),這就是固定頭部重疊您的部分的原因。
我建議你使用假ids,如下所示:
window.location.hash = '!' + id;
然后,當你加載頁面時......
gotoByScroll(windwo.location.hash.substr(2);
這樣,頁面中沒有帶有該id的元素,並且沒有第二個滾動。
希望這有效。
首先保存當前滾動位置,然后更改散列,然后應用保存的滾動位置,然后應用動畫。
var target = $(id).offset().top - offset,
scrollmem = $('html, body').scrollTop();
window.location.hash = id;
$('html, body').scrollTop(scrollmem).animate({ scrollTop: target }, 500, function () {
// nothing here
});
如果使用插件不是問題,請使用jQuery ScrollTo插件: http : //demos.flesler.com/jquery/scrollTo/
此外,如果您已經在使用event.preventDefault()
,則不需要使用return false;
防止''標簽的默認點擊行為
我做了另一個解決方案。
// The id of the section we want to go to.
var id = $(this).attr("href"),
$id = $(id),
dataID = id.substr(1);
// Our scroll target : the top position of the
// section that has the id referenced by our href.
var target = $(id).offset().top - offset;
$id.attr('data-id',dataID).attr('id','');
window.location.hash = id;
$id.attr('id',dataID);
$('html,body').animate({scrollTop: target},500);
這樣做是在更改哈希值之前刪除目標元素上的“id”(傳遞給data-id
屬性)以防止跳轉(因為在文檔中找不到),然后在更改后將其添加回來。
如果你只是需要你的id來定位你的部分你可以給它們不同的名字而不是你的主題標簽(確保頁面中不存在主題標簽);
HTML:
<section id="section-portfolio">...</section>
JS:
var id = $(this).attr("href").substr(1);
var target = $("#section-"+id).offset().top - offset;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.