简体   繁体   中英

Trigger jQuery function at specific different browser widths

So I have this jQuery function that adds margin-top to an element based on the height of another element.

I'm trying to have this function trigger again on window resizes. (Preferably 1200px, 991px, 768px, 500px breakpoints)

If there is a good solution that allows the function to trigger with any browser resize, even better. I just need to make sure this wont cause "lag" or "slowness" due to the function triggering 100 times during a resize event for example.

Here is a codepenn with my current function:

http://codepen.io/bruno-gomes/pen/vgRbBB

Code:

jQuery(document).ready(function($) {
    (function() {
        var navBarHeight = $('.header').height();
        $('.content').css('margin-top', navBarHeight);
    })();
});

The idea is that I want the fixed header to not cover the content, and the size of the header will vary depending on the width of the browser. This becomes an issue when user resizes browser because the function is only triggering once on load.

I have the IIFE setup like that because it's a Joomla site and they don't work properly otherwise by the way.

您可以使用.resize()

Ok seems like this approach solved all my problems ^.^

jQuery(document).ready(function($) {
  var height = $('.header').height();
  resizeHeader(height);
  $(window).resize(function() {
    var height = $('.header').height();
    resizeHeader(height);
  });
  function resizeHeader(height) {
   $('.content').css('margin-top', height);
  }
});

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