繁体   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