简体   繁体   English

导航栏滚动上的徽标克隆

[英]Logo cloning on navbar scroll

I have the following script:我有以下脚本:

$(function() {
  var header = $(".header-nav");

  $(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll >= 50) {
      header.addClass("scrolled");
    }
    if (scroll > 50 && scroll < 60) {
      $(".header_logo img").clone().appendTo(".header-logo");
    }
    if (scroll <= 50) {
      header.removeClass("scrolled");
    }
  });

});

It's supposed to make the navbar fixed on scroll and clone the website logo to the navba r on a .header-logo empty div它应该使navbar固定在滚动和克隆网站标志的navba R ON一个.header-logodiv

But it doesn't work as expected.但它没有按预期工作。 The logo is mass duplicated or don't appear until a top scrolling.徽标被大量复制或直到顶部滚动才出现。

Is there a way to make it work as: When I scroll, the logo is cloned one time on the navbar then disappear if you go back to top page?有没有办法让它工作:当我滚动时,徽标在navbar上克隆一次,然后如果返回首页则消失?

Thanks谢谢

Clone img outside the condition, then append or remove based on your if condition.在条件之外克隆img ,然后根据您的if条件追加或删除。 You need to set a class to detect cloned img for removing.您需要设置一个class来检测要删除的克隆img

 $(function() { var header = $(".header-nav"); $el = $(".header-logo img").clone().addClass('cloned'); $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll >= 50) { header.addClass("scrolled"); } else { header.removeClass("scrolled"); } if (scroll > 50) { $el.appendTo(".header-logo"); } else { $('.cloned').remove(); } }); });
 body { height: 1000px; /* fake height! */ } header.header-nav.scrolled { position: fixed; } .header-nav { background: white; width: 100%; min-height: 150px; border: 1px solid gray; } .scrolled { background: red; } .header-logo img { height: 150px; display: block; margin: auto; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <header class="header-nav"> <div class="header-logo"> <img src="https://i.graphicmama.com/blog/wp-content/uploads/2019/10/02145410/logo-design-trends-2020-colorful-gradient-logos-example-1.gif" /> </div> </header>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM