【问题标题】:Is this jQuery correct?这是 jQuery 正确的吗?
【发布时间】:2015-06-26 01:51:06
【问题描述】:

我想在我的页面上有平滑的滚动效果。并且 iv 找到了这段代码

jQuery(function($) {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

这没问题,但不适用于我的“转到顶部”链接。所以我用教程检查其他页面并这样做:

jQuery(function($) {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
  $('a.go-top').click(function() {
    $('html, body').animate({scrollTop:0}, 'slow');
    return false;
  });
});

现在一切正常。但我对jQuery一无所知,你能告诉我这是正确的代码吗,或者如果可以,我应该在这里改变什么?谢谢!

【问题讨论】:

  • 我觉得这个问题应该发到Code Review
  • @ArturFilipiak 要成为代码审查的主题,问题必须由代码的作者或维护者提出。您不能只要求对您发现的随机代码进行代码审查。
  • @ArturFilipiak 一定是作者本人。 Artur,看看this。页面底部附近有一个小清单 - 如果您以“是”回答所有问题,它应该在 CodeReview 上。其中一个问题要求作者提出
  • 或维护者。哎呀。

标签: jquery scroll smooth


【解决方案1】:

它不适用于您的 go top 链接,因为您只在寻找具有要单击的 id 属性的链接:$('a[href*=#]:not([href=#])')。你的go-top 是一个类而不是一个id,如果你把它改成一个id,你就不需要你添加的代码了。

【讨论】:

  • 感谢您的回答,iv 将其更改为 id 但仍然无法正常工作。我在代码中的内容://* 在页脚 add_filter("genesis_structural_wrap-footer-widgets", 'sp_add_content_to_footer_wrap', 10, 2);函数 sp_add_content_to_footer_wrap( $output, $original_output ) { if( 'open' == $original_output ) { $output = '' 。 $输出; } 返回 $ 输出; }
  • 令人惊讶的是,这并不难读哈哈。那么你必须考虑你的代码在做什么<a href="#" id="go-top">。这是链接到哪里?答案是它没有链接到你只是把井号放在里面的任何地方。再说一次,你认为这段代码做了什么$('a[href*=#]:not([href=#])')。它与您实现的具体不匹配,即<a href="#">。您想将<a href=#> 更改为<a href="wherever you want">
  • 既然你想转到页面顶部,你应该在页面顶部创建一个 div,如 <div id='top'> 并将 <a href="#"> 更改为 <a href="div#top">
  • 我正在为 WordPress 使用 genesis 主题,顶部没有任何 id 元素,所以如果我无法链接到任何 # 我必须使用此附加代码:$('a.go -top').click(function() { $('html, body').animate({scrollTop:0}, 'slow'); return false; }); ?
  • 保留您的附加代码是最简单的方法。
猜你喜欢
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多