jQuery函数相互覆盖

时间:2018-10-26 23:25:52

标签: jquery

我有这3个功能,我认为平滑滚动功能会覆盖图像模糊功能或其他功能,但我不知道问题出在哪里。如果我注释掉平滑滚动功能,则图像背景模糊功能将起作用。

下面是jQuery函数,有人可以解决吗?

//////////////////////// Smooth Scroll To Specific Element On Page ////////////////////////
$(document).ready(function($) {
    $('a[href^="#"]').not('.nav-link').bind('click.smoothscroll', function(e) {
        e.preventDefault();

        var hash = this.hash;

        jQuery('html, body').animate({
            scrollTop: jQuery(hash).offset().top - 60
        }, 1500, function(){});
    });
});

//////////////////////// Smooth Scroll To Specific Element On Different Page ////////////////////////

$(document).ready(function(){
    var urlHash = window.location.href.split("#")[1];
    if (urlHash.length > 0)
        $('html,body').animate({
            scrollTop: $('#' + urlHash).offset().top - 60
        }, 2500);
});

//////////////////////// Background Image Blur ////////////////////////

$(document).ready(function() {
    $(window).scroll(function(e) {
        var s = $(window).scrollTop(),
        opacityVal = (s / 1000);

        $('.blurred-image').css('opacity', opacityVal);
    });
});

1 个答案:

答案 0 :(得分:0)

我看到的唯一问题是这两行:

var urlHash = window.location.href.split("#")[1];
if (urlHash.length > 0)

没有哈希值时,urlHash是未定义的,检查其length会引发错误:

  

未捕获的TypeError:无法读取未定义的属性'length'

这将导致其余代码进入not be executed
我已经这样处理了:

var urlHash = window.location.href.split("#")[1] || false;

除此之外,您不需要多个document.ready函数。
won't break your code,只是没有必要。

$(function() {

  // Smooth Scroll To Specific Element On Page

  $('a[href^="#"]').not('.nav-link').on('click', function(e) {

    e.preventDefault();

    var hash = this.hash;

    $('html, body').animate({
      scrollTop: $(hash).offset().top - 60
    }, 1500, function() {});

  });


  // Smooth Scroll To Specific Element On Different Page

  var urlHash = window.location.href.split("#")[1] || false;

  if (urlHash.length > 0) {
    $('html,body').animate({
      scrollTop: $('#' + urlHash).offset().top - 60
    }, 2500);
  }


  // Background Image Blur

  $(window).scroll(function(e) {

    var s = $(window).scrollTop();
    var opacityVal = (s / 1000);

    $('.blurred-image').css('opacity', opacityVal);

  });

});
img {
  display: block;
  margin: 1em 0;
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#stuff">Scroll To Stuff</a>

<img src="https://picsum.photos/200/300?image=0" alt="" class="blurred-image">
<img src="https://picsum.photos/200/300?image=10" alt="" class="blurred-image">
<img src="https://picsum.photos/200/300?image=20" alt="" class="blurred-image">
<img src="https://picsum.photos/200/300?image=30" alt="" class="blurred-image">
<img src="https://picsum.photos/200/300?image=40" alt="" class="blurred-image">

<div id="stuff">
  STUFF
</div>

相关问题