简体   繁体   中英

Javascript changes on window size

I am trying to make my javascript change when the window resizes, but cannot seem to get it to work. The only difference I would like is for the offset().top to change from -90 to -60 as the window becomes smaller than 768px.

This is what I have so far:

$(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-90
        }, 1000);
        return false;
      }
    }
  });
});

$(window).resize(function(){
    if ($(window).width() <= 768){  
        $(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-60
                }, 1000);
                return false;
              }
            }
          });
        });
    }   
});

Any advice would be really great!

Thank you

The first click event handler $('a[href*=#]:not([href=#])').click is binded everytime the js is run.

On resize you attach a second handler to click event - it is NOT overwritting the first one - so there are two event handlers attached for one event. I guess you want first do sth like $('a[href*=#]:not([href=#])').off('click'); to unbind first event handler on window resize and then attach the second one.

But since you are changing only one small piece of code you'd rather write:

    $(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 - ( ($(window).width() <= 768) ? 60 : 90)
            }, 1000);
            return false;
          }
        }   
        }); 
    });

Note the scrollTop line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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