dtlhy0771 2016-08-14 19:04
浏览 68

同一页面上的平滑滚动无法正常工作

I'm trying to achieve smooth scrolling on same page using PHP code inside jQuery(trying to generate final jquery code using PHP). But for some reason it's not working, I'd appreciate if anyone can point out the errors or why it's not working

// When the Document Object Model is ready
   jQuery(document).ready(function(){
   // 'scroll' is the amount of pixels destination
   // is from the top of the document
   var scroll = jQuery('<?php echo get_option('smooth_scroll'); ?>').offset().top;

// When button is clicked
  jQuery('.test').click(function(){
   // Scroll down to 'scroll'
   jQuery('html, body').animate({scrollTop:scroll}, 'slow');
   // Stop the link from acting like a normal anchor link
   return false;
  });
});

I have a href link with class "test" in it. When that button is clicked I want it to smooth scroll to go a specific div of the same page[thru get_option('smooth_scroll')] div will be updated by users).

  • 写回答

1条回答 默认 最新

  • duanba8070 2016-08-14 19:27
    关注

    First of all - please try to move the scroll variable assignment into the click event:

    jQuery(function(){
      jQuery('.test').on('click', function(e){
        e.preventDefault();
        var scroll = jQuery('<?php echo get_option('smooth_scroll'); ?>').offset().top;
        jQuery('html, body').animate({scrollTop:scroll}, 'slow');
      });
    });
    

    Because currently you can have a situation when your element is not on its final position - as it is calculated on DOMContentLoaded event, which is called after loading complete DOM structure, but CSS/JS/image assets can be not loaded at this moment, what can affect the calculation result.

    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等