1

我是 jQuery 的新手,所以我在继续学习。

在我正在创建的网站上,有 2 个功能似乎相互冲突:第一个是当用户开始滚动时网站的标题会淡出,第二个是用于在页面上的锚点之间平滑滚动。第二个脚本使淡出脚本即使没有用户滚动也会立即运行。

这是一个显示这个想法的小提琴:http: //jsfiddle.net/Mvf67/284/

这是代码:

// fade out
$(document).ready(function () {
    $(window).scroll(function () {
        $(".title").fadeOut(1000);
    });
});

// smooth scroll
$(document).ready(function () {
    function filterPath(string) {
        return string.replace(/^\//, '')
        .replace(/(index|default).[a-zA-Z]{3,4}$/, '')
        .replace(/\/$/, '');
    }
    var locationPath = filterPath(location.pathname);
    var scrollElem = scrollableElement('html', 'body');

    $('a[href*=#]').each(function () {
        var thisPath = filterPath(this.pathname) || locationPath;
        if (locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/, '')) {
            var $target = $(this.hash),
            target = this.hash;
            if (target) {
                 var targetOffset = $target.offset().top;
                 $(this).click(function (event) {
                     event.preventDefault();
                     $(scrollElem).animate({
                         scrollTop: targetOffset
                     }, 1500, function () {
                         location.hash = target;
                     });
                 });
            }
       }
  });

  function scrollableElement(els) {
      for (var i = 0, argLength = arguments.length; i < argLength; i++) {
          var el = arguments[i],
          $scrollElement = $(el);
          if ($scrollElement.scrollTop() > 0) {
              return el;
          } else {
              $scrollElement.scrollTop(1);
              var isScrollable = $scrollElement.scrollTop() > 0;
              $scrollElement.scrollTop(0);
              if (isScrollable) {
                  return el;
              }
          }
      }
      return [];
   }

});

任何人都可以帮忙吗?

提前致谢。

编辑:小提琴链接已修复

4

1 回答 1

3

只保留一个document.ready功能而不是两个

于 2013-04-02T10:22:28.757 回答