撒科打諢
2019-07-23 19:42:34
在沒有頁面滾動的情況下修改location.hash我們有一些頁面使用ajax來加載內容,并且在某些情況下我們需要深入鏈接到頁面。而不是鏈接到“用戶”并告訴人們點擊“設置”,能夠將人們鏈接到user.aspx#settings是有幫助的為了讓人們能夠為我們提供正確的部分鏈接(用于技術支持等),我已將其設置為在點擊按鈕時自動修改URL中的哈希值。唯一的問題當然是,當發生這種情況時,它還會將頁面滾動到此元素。有沒有辦法禁用它?以下是我到目前為止這樣做的方法。$(function(){
//This emulates a click on the correct button on page load
if(document.location.hash){
$("#buttons li a").removeClass('selected');
s=$(document.location.hash).addClass('selected').attr("href").replace("javascript:","");
eval(s);
}
//Click a button to change the hash
$("#buttons li a").click(function(){
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash=$(this).attr("id")
//return false;
});});我曾希望return false;會阻止頁面滾動 - 但它只會使鏈接無法正常工作。所以現在只是注釋掉,所以我可以導航。有任何想法嗎?
3 回答
慕后森
TA貢獻1802條經驗 獲得超5個贊
步驟1:您需要解除節點ID,直到設置了哈希。這是通過在設置哈希時從節點中刪除ID,然后重新添加它來完成的。
hash = hash.replace( /^#/, '' );var node = $( '#' + hash );if ( node.length ) {
node.attr( 'id', '' );}document.location.hash = hash;if ( node.length ) {
node.attr( 'id', hash );}第2步:某些瀏覽器會根據上次看到ID'd節點的位置觸發滾動,因此您需要稍微幫助它們。您需要div在視口頂部添加一個額外的內容,將其ID設置為哈希值,然后將所有內容回滾:
hash = hash.replace( /^#/, '' );var fx, node = $( '#' + hash );if ( node.length ) {
node.attr( 'id', '' );
fx = $( '<div></div>' )
.css({
position:'absolute',
visibility:'hidden',
top: $(document).scrollTop() + 'px'
})
.attr( 'id', hash )
.appendTo( document.body );}document.location.hash = hash;if ( node.length ) {
fx.remove();
node.attr( 'id', hash );}第3步:將其包裝在插件中并使用它而不是寫入location.hash...
白板的微信
TA貢獻1883條經驗 獲得超3個贊
我想我可能找到了一個相當簡單的解決方案。問題是URL中的哈希值也是您滾動到的頁面上的元素。如果我只是將一些文本添加到哈希,現在它不再引用現有元素!
$(function(){
//This emulates a click on the correct button on page load
if(document.location.hash){
$("#buttons li a").removeClass('selected');
s=$(document.location.hash.replace("btn_","")).addClass('selected').attr("href").replace("javascript:","");
eval(s);
}
//Click a button to change the hash
$("#buttons li a").click(function(){
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash="btn_"+$(this).attr("id")
//return false;
});});現在,URL顯示為page.aspx#btn_elementID不是頁面上的真實ID。我只是刪除“btn_”并獲取實際的元素ID
慕俠2389804
TA貢獻1719條經驗 獲得超6個贊
使用history.replaceState或history.pushState*更改哈希值。這不會觸發跳轉到相關元素。
例
$(document).on('click', 'a[href^=#]', function(event) {
event.preventDefault();
history.pushState({}, '', this.href);});*如果您想要歷史向前和向后支持
歷史行為
如果您正在使用history.pushState并且當用戶使用瀏覽器的歷史記錄按鈕(向前/向后)時您不想要頁面滾動,請查看實驗scrollRestoration設置(僅限Chrome 46+)。
history.scrollRestoration = 'manual';
瀏覽器支持
添加回答
舉報
0/150
提交
取消
