【问题标题】:Conflicting "back to top" scripts - how to fix?冲突的“回到顶部”脚本 - 如何解决?
【发布时间】:2014-07-02 19:30:17
【问题描述】:

我使用了 2 个在 Internet 上找到的脚本,一个用于平滑滚动到页面底部的 DIV,另一个用于平滑滚动“返回顶部”。问题是两者之间存在冲突,因此“返回顶部”不起作用(点击时没有返回顶部)。单独使用它们都可以完美地工作。

如何将它们“合并”到一个脚本中? (并保留back to top脚本的淡入淡出效果)见http://jsfiddle.net/GjsVq/1/

非常感谢

$(document).ready(function() {
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();

        var target = this.hash,
        $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});


$(document).ready(function() {
    var offset = 220;
    var duration = 500;
    jQuery(window).scroll(function() {
        if (jQuery(this).scrollTop() > offset) {
            jQuery('.back-to-top').fadeIn(duration);
        } else {
            jQuery('.back-to-top').fadeOut(duration);
        }
    });

    jQuery('.back-to-top').click(function(event) {
        event.preventDefault();
        jQuery('html, body').animate({scrollTop: 0}, duration);
        return false;
    })
});

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    $('a[href^="#"]').on(... 选择了两个<a> 元素。一种方法是重写此选择器以仅匹配应强制滚动到底部的 <a> 元素(也许为此使用 CSS 类?)

    另一种快速而简单的解决方法是在附加其自己的点击处理程序之前重置“back-to-top”元素上的事件处理程序:jQuery('.back-to-top').off().click(...

    【讨论】:

      【解决方案2】:

      我通常只使用一个平滑滚动功能,然后使用 href="#idOfHighestElementOnPage" 设置我的“转到顶部”按钮。这是平滑滚动功能(如果您不想走我走的同一条路线,它可能包括一些有用的东西):

      $(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 - 100
                  }, 'normal');
                  return false;
              }
          }
      });
      })
      
      window.onscroll = scrollFunction;
      function scrollFunction() {
          var doc = document.documentElement, body = document.body;
          var top = (doc && doc.scrollTop  || body && body.scrollTop  || 0);
          if (top > 200) {
              $('.back-to-top').fadeIn();
          }
          else {
              $('.back-to-top').fadeOut();
          }
      }
      

      【讨论】:

      • 谢谢,但在那种情况下,不幸的是,我失去了返回顶部按钮的淡入淡出效果
      猜你喜欢
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2022-12-20
      • 2022-12-18
      • 2014-12-27
      相关资源
      最近更新 更多