【问题标题】:Why jquery scroll function load well only after the second or third time of use?为什么 jquery 滚动功能只有在第二次或第三次使用后才能很好地加载?
【发布时间】:2019-04-06 21:48:46
【问题描述】:

Jquery 滚动功能仅在第二次和第三次使用时加载良好。 页面加载后它不能正常工作。我设置的 transition-duration 是逐步工作的,不像第二次或第三次之后那样顺利。

我使用$(window).on('load', function() { ... });函数,所有脚本标签都在结束body标签之前。

$(window).on('load', function() {

            // navbar scroll things
  $(window).scroll(function() {
    if ($(document).scrollTop() > 50) {
      $(".navbar").addClass("shrink");
      $(".navbar").removeClass("bg-transparent");
      $(".navbar img").attr("src", "img/logo_fekete.png");
    } else {
      $(".navbar").removeClass("shrink");
      $(".navbar img").attr("src", "img/logo_feher.png");
    }
  });

  // Add smooth scrolling to all links
  $(".scroll").on("click", function(event) {
    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();
      // Store hash
      var hash = this.hash;
      $("html, body").animate({
        scrollTop: $(hash).offset().top
      }, 850, function(){
        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });

});

实际结果可以看那里: http://bgydesigntest.000webhostapp.com

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    尝试改用jQuery ready() 方法。这将允许您的 jQuery 方法在您的 HTML 文档加载后立即加载。

    $(document).ready(function(){
    
                // navbar scroll things
      $(window).scroll(function() {
        if ($(document).scrollTop() > 50) {
          $(".navbar").addClass("shrink");
          $(".navbar").removeClass("bg-transparent");
          $(".navbar img").attr("src", "img/logo_fekete.png");
        } else {
          $(".navbar").removeClass("shrink");
          $(".navbar img").attr("src", "img/logo_feher.png");
        }
      });
    
      // Add smooth scrolling to all links
      $(".scroll").on("click", function(event) {
        // Make sure this.hash has a value before overriding default behavior
        if (this.hash !== "") {
          // Prevent default anchor click behavior
          event.preventDefault();
          // Store hash
          var hash = this.hash;
          $("html, body").animate({
            scrollTop: $(hash).offset().top
          }, 850, function(){
            // Add hash (#) to URL when done scrolling (default click behavior)
            window.location.hash = hash;
          });
        } // End if
      });
    
    });
    

    【讨论】:

    • 这样更好,谢谢!我还使第二个徽标的尺寸更小,因此加载速度更快。这样一切正常。
    • 太好了……很高兴知道这一点
    猜你喜欢
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    相关资源
    最近更新 更多