簡體   English   中英

jQuery鏈接到頁面加載后的div id-但是頁面在動畫后繼續加載

[英]jquery linking to div id after page load - but page continues to load after animate

此任務的總體目標是使用戶滾動到頁面下方某個div的動畫上,具體取決於將#hashName附加到url的內容。

我正在使用的html沒有添加正確的div id,因此我通過文檔准備就緒的javascript進行添加。 添加div ID后,我便擁有了腳本,該腳本確定傳入的哈希,然后將用戶傳遞給哈希。 以下代碼有效:

jQuery(document).ready(function($){
    //append new div id to current FAQ class
    document.querySelector('.press-24_tab').id = 'faq';

    //now that we have correct div id, animate user to this div
       var target = window.location.hash;

       $('html, body').animate({scrollTop: $(window.location.hash).offset().top}, 'slow', function() {
            //in animate callback, attempt to keep user focused here
            $('#faq').focus();
        });
});

我在代碼中調用jQuery等,因此可以在WordPress中使用它。

此代碼可以正常工作。 我的問題是, 頁面加載這個腳本觸發。 並且頁面不斷加載。 結果,頁面焦點回到頁面頂部!

我當時正在考慮將動畫包裹在$(window).on('load', function(){});哈希代碼中$(window).on('load', function(){}); 但這似乎不起作用。 請注意,我現有的動畫回調試圖使用戶保持專注-但這並不持久。 頁面仍然加載。 Page需要花很長的時間才能加載,所以我正在與之抗爭。

因此,在這一點上,我碰到了磚牆。 我正在與那些比我精通javascript和jQuery的人聯系,看看我在這里要做的事情。 任何幫助將不勝感激。

DOM准備就緒后將立即觸發 jquery(document).ready()因此,由於DOM與文檔本身不同,因此它實際上可以按事物的外觀運行。

如果您需要等待外部內容(例如網絡字體,圖像,視頻等),則應使用window.load()事件

jquery(window).load(function() {
  //append new div id to current FAQ class
  document.querySelector('.press-24_tab').id = 'faq';

  //now that we have correct div id, animate user to this div
  var target = window.location.hash;

  $('html, body').animate({
    scrollTop: $(window.location.hash).offset().top
  }, 'slow', function() {
    //in animate callback, attempt to keep user focused here
    $('#faq').focus();
  });
});

在此處瀏覽 DOM文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM