简体   繁体   English

在特定的不同浏览器宽度下触发jQuery函数

[英]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. 所以我有这个jQuery函数,它根据另一个元素的高度将margin-top添加到一个元素。

I'm trying to have this function trigger again on window resizes. 我试图让此函数在窗口调整大小时再次触发。 (Preferably 1200px, 991px, 768px, 500px breakpoints) (最好是1200px,991px,768px,500px断点)

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. 我只需要确保不会由于函数在调整大小事件期间触发100次而导致“滞后”或“缓慢”。

Here is a codepenn with my current function: 这是我当前功能的代码penn:

http://codepen.io/bruno-gomes/pen/vgRbBB 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. 我有这样的IIFE设置,因为它是一个Joomla网站,否则它们不能正常工作。

您可以使用.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);
  }
});

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

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