2017-05-15 4 views
0

私はthis websiteに反応しています。これはJavaScriptを使用してすべてのページにindex.htmlをロードする静的なHTML Webサイトです。JavaScriptはURLに#を入れ、新しいページが途中で開きます

問題はJavaScriptコードがすべてのリンクの前に#を配置することです。ページの途中でリンクをクリックすると、途中で新しいページが開きます(古いページ上のリンクと同じスクロール位置)。

新しいページを常にページの上部で開くことができますか?

JavaScriptファイルは、(私にはちんぷんかんぷんです...)以下のスクリプト

var ScriptJS = true; 
var lastLocation = document.location.href; 

$(document).ready(function() { 
if (!$('#ajax').length) { // Check if index.html was loaded. If not, navigate to index.html and load the hash part with ajax. 
    document.location = document.location.href.substring(0, 
document.location.href.lastIndexOf('/') + 1) + 
     "#" + 
document.location.href.substr(document.location.href.lastIndexOf('/') + 1); 
} 

if (window.location.hash) // Check if the page is being loaded with a '#'. Load the file. 
    $('#ajax').load(window.location.hash.substr(1)); 
}); 

$(document).on("click", "a:not(.regular)", function (e) { 
var url = this.href; 
if (url.indexOf("https") != -1 || url.indexOf('.html') == -1) // External link or picture 
    return; 

e.preventDefault(); 

$('#ajax').load(url, function() { 
    var pagename = url.substr(url.lastIndexOf('/') + 1); 
    lastLocation = document.location.href.replace(window.location.hash, "") 
+ '#' + pagename; 
    document.location.href = '#' + pagename; 
}); 
}); 

window.onpopstate = function (event) { 
if (lastLocation != document.location.href) 
    location.reload(); 
else 
    return; 
}; 
+1

'document.location.href = '#' + pagename;はあなたの犯人のようです。 – sesamechicken

答えて

1

が含まれているスクリプトは、新しいページをフェッチし、ロードされたコンテンツを、現在のページの内容を置き換えるためにAJAXを使用しています。

「#ページ名」は、おそらくブラウザの戻るボタンを操作するためのものです。あなたがそれを望まないなら、それをコメントすることができますが、あなたは同じ振る舞いをします。

document.location.href = ...行の後ろにdocument.body.scrollTop = 0;を設定します。

+0

あなたの責任David(とSesamechickenももちろん)のおかげで、これはうまくいくようです! –

+0

HmmmこれはFireFoxやIE11では動作しないようです... Chrome、Edge、Android、およびIphoneで動作します。助言がありますか? –

+0

@Bob:スクロールはブラウザによって異なるコンテナに表示されます。あなたがjQuery '$( 'html、body')を使っているので、scrollTop(0)'は両方に対応する必要があります。 –

関連する問題