如何在加載頁面時禁用錨點“跳轉”?我認為這可能是不可能的,我會盡力解釋。我有一個包含選項卡(jquery powered)的頁面,由以下內容控制:我正在使用此代碼,由前一個問題中的其他用戶提供。<script type="text/javascript">
$(function() {
$('html, body').animate({scrollTop:0}); // this is my "fix"
var tabContent = $(".tab_content");
var tabs = $("#menu li");
var hash = window.location.hash;
tabContent.not(hash).hide();
if(hash=="") {
$('#tab1').fadeIn();
}
tabs.find('[href=' + hash + ']').parent().addClass('active');
tabs.click(function() {
$(this).addClass('active').siblings().removeClass('active');
tabContent.hide();
var activeTab = $(this).find("a").attr("href");
$(activeTab).fadeIn();
return false;
});
});</script>當我直接訪問“標簽頁”時,此代碼非常有用。但是,我需要鏈接到其他頁面的invidual標簽 - 所以要做到這一點,代碼獲取window.location.hash然后顯示適當的選項卡。由于“返回false”,頁面不會“跳轉”到錨點。但是,此事件僅在單擊事件時觸發。因此,如果我從任何其他頁面訪問我的“標簽”,則會觸發“跳轉”效果。為了解決這個問題,我自動滾動到頁面頂部,但我寧愿這不會發生。是否有任何方法可以在頁面加載時模擬“返回false”,從而防止錨點“跳轉”。希望這很清楚。謝謝
3 回答

犯罪嫌疑人X
TA貢獻2080條經驗 獲得超4個贊
你的修復不起作用嗎?我不確定我是否正確理解了這個問題 - 你有一個演示頁嗎?你可以嘗試:
if (location.hash) { setTimeout(function() { window.scrollTo(0, 0); }, 1);}
編輯:經過測試,適用于Windows上的Firefox,IE和Chrome。
編輯2:移動setTimeout()
內部if
塊,道具@vsync。

蝴蝶不菲
TA貢獻1810條經驗 獲得超4個贊
訣竅是只刪除主題標簽ASAP并存儲其值供您自己使用:
重要的是你不要把這部分代碼放在$()或$(window).load()函數中,因為它會延遲并且瀏覽器已經移動到標記。
// store the hash (DON'T put this code inside the $() function, it has to be executed // right away before the browser can start scrolling!var target = window.location.hash, target = target.replace('#', '');// delete hash so the page won't scroll to itwindow.location.hash = "";// now whenever you are ready do whatever you want// (in this case I use jQuery to scroll to the tag after the page has loaded)$(window).on('load', function() { if (target) { $('html, body').animate({ scrollTop: $("#" + target).offset().top }, 700, 'swing', function () {}); }});

桃花長相依
TA貢獻1860條經驗 獲得超8個贊
還有其他方法可以跟蹤您所使用的標簽; 也許設置一個cookie,或隱藏字段中的值等等。
我會說,如果你不希望頁面在加載時跳轉,你最好使用其中一個選項而不是哈希,因為使用哈希優先于它們的主要原因是準確地允許你我想要阻止。
另一點 - 如果您的哈希鏈接與文檔中的標記名稱不匹配,頁面將不會跳轉,因此,如果您想繼續使用哈希,您可以操縱內容以便標記的名稱不同。如果您使用一致的前綴,您仍然可以使用Javascript在之間跳轉。
希望有所幫助。
- 3 回答
- 0 關注
- 977 瀏覽
添加回答
舉報
0/150
提交
取消