jQuery 调整窗口大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9828831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:21:31  来源:igfitidea点击:

jQuery on window resize

jqueryhtmlcss

提问by ediblecode

I have the following JQuery code:

我有以下 JQuery 代码:

$(document).ready(function () {
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
    if ($containerHeight > 819) {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    }
});

The only problem is that this only works when the browser first loads, I want containerHeightto also be checked when they are resizing the window?

唯一的问题是这仅在浏览器首次加载时有效,我想containerHeight在调整窗口大小时也进行检查?

Any ideas?

有任何想法吗?

回答by Cory Danielson

Here's an example using jQuery, javascript and css to handle resize events.
(css if your best bet if you're just stylizing things on resize (media queries))
http://jsfiddle.net/CoryDanielson/LAF4G/

这是一个使用 jQuery、javascript 和 css 处理调整大小事件的示例。
(如果您只是在调整大小(媒体查询)时对事物进行样式化,则最好选择 css)
http://jsfiddle.net/CoryDanielson/LAF4G/

css

css

.footer 
{
    /* default styles applied first */
}

@media screen and (min-height: 820px) /* height >= 820 px */
{
    .footer {
        position: absolute;
          bottom: 3px;
          left: 0px;
        /* more styles */
    }
}

javascript

javascript

window.onresize = function() {
    if (window.innerHeight >= 820) { /* ... */ }
    if (window.innerWidth <= 1280) {  /* ... */ }
}

jQuery

jQuery

$(window).on('resize', function(){
      var win = $(this); //this = window
      if (win.height() >= 820) { /* ... */ }
      if (win.width() >= 1280) { /* ... */ }
});

How do I stop my resize code from executing so often!?

如何阻止我的调整大小代码如此频繁地执行!?

This is the first problem you'll notice when binding to resize. The resize code gets called a LOT when the user is resizing the browser manually, and can feel pretty janky.

这是绑定调整大小时您会注意到的第一个问题。当用户手动调整浏览器大小时,调整大小代码会被调用很多,并且会感觉很笨拙。

To limit how often your resize code is called, you can use the debounceor throttlemethods from the underscore& lowdashlibraries.

要限制调用调整大小代码的频率,您可以使用underscorelowdash库中的去抖动节流方法。

  • debouncewill only execute your resize code X number of milliseconds after the LAST resize event. This is ideal when you only want to call your resize code once, after the user is done resizing the browser. It's good for updating graphs, charts and layouts that may be expensive to update every single resize event.
  • throttlewill only execute your resize code every X number of milliseconds. It "throttles" how often the code is called. This isn't used as often with resize events, but it's worth being aware of.
  • debounce将仅在 LAST 调整大小事件后执行您的调整大小代码 X 毫秒。当您只想在用户完成浏览器大小调整后调用一次调整大小代码时,这是理想的选择。它适用于更新图形、图表和布局,因为更新每个调整大小事件的成本可能很高。
  • throttle只会每 X 毫秒执行一次调整大小代码。它“限制”了代码被调用的频率。这不常用于调整大小事件,但值得注意。

If you don't have underscore or lowdash, you can implement a similar solution yourself: JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

如果您没有下划线或低破折号,您可以自己实现类似的解决方案: JavaScript/JQuery: $(window).resize 如何在调整大小完成后触发?

回答by Matthew Darnell

Move your javascript into a function and then bind that function to window resize.

将您的 javascript 移动到一个函数中,然后将该函数绑定到窗口大小调整。

$(document).ready(function () {
    updateContainer();
    $(window).resize(function() {
        updateContainer();
    });
});
function updateContainer() {
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
    if ($containerHeight > 819) {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    }
}

回答by Adam

jQuery has a resize event handler which you can attach to the window, .resize(). So, if you put $(window).resize(function(){/* YOUR CODE HERE */})then your code will be run every time the window is resized.

jQuery 有一个 resize 事件处理程序,您可以将其附加到窗口.resize()。因此,如果您放置,$(window).resize(function(){/* YOUR CODE HERE */})则每次调整窗口大小时都会运行您的代码。

So, what you want is to run the code after the first page load and whenever the window is resized. Therefore you should pull the code into its own function and run that function in both instances.

因此,您想要的是在第一页加载后以及窗口调整大小时运行代码。因此,您应该将代码拉入其自己的函数并在两个实例中运行该函数。

// This function positions the footer based on window size
function positionFooter(){
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
    else {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    } 
}

$(document).ready(function () {
    positionFooter();//run when page first loads
});

$(window).resize(function () {
    positionFooter();//run on every window resize
});

See: Cross-browser window resize event - JavaScript / jQuery

请参阅:跨浏览器窗口调整大小事件 - JavaScript / jQuery

回答by vitro

Try this solution. Only fires once the page loads and then during window resize at predefined resizeDelay.

试试这个解决方案。仅在页面加载后触发,然后在预定义的窗口调整大小期间触发resizeDelay

$(document).ready(function()
{   
   var resizeDelay = 200;
   var doResize = true;
   var resizer = function () {
      if (doResize) {

        //your code that needs to be executed goes here

        doResize = false;
      }
    };
    var resizerInterval = setInterval(resizer, resizeDelay);
    resizer();

    $(window).resize(function() {
      doResize = true;
    });
});

回答by gpasci

Give your anonymous function a name, then:

给你的匿名函数一个名字,然后:

$(window).on("resize", doResize);

http://api.jquery.com/category/events/

http://api.jquery.com/category/events/

回答by hdf54d56

can use it too

也可以用

        function getWindowSize()
            {
                var fontSize = parseInt($("body").css("fontSize"), 10);
                var h = ($(window).height() / fontSize).toFixed(4);
                var w = ($(window).width() / fontSize).toFixed(4);              
                var size = {
                      "height": h
                     ,"width": w
                };
                return size;
            }
        function startResizeObserver()
            {
                //---------------------
                var colFunc = {
                     "f10" : function(){ alert(10); }
                    ,"f50" : function(){ alert(50); }
                    ,"f100" : function(){ alert(100); }
                    ,"f500" : function(){ alert(500); }
                    ,"f1000" : function(){ alert(1000);}
                };
                //---------------------
                $(window).resize(function() {
                    var sz = getWindowSize();
                    if(sz.width > 10){colFunc['f10']();}
                    if(sz.width > 50){colFunc['f50']();}
                    if(sz.width > 100){colFunc['f100']();}
                    if(sz.width > 500){colFunc['f500']();}
                    if(sz.width > 1000){colFunc['f1000']();}
                });
            }
        $(document).ready(function() 
            {
                startResizeObserver();
            });

回答by WynandB

function myResizeFunction() {
  ...
}

$(function() {
  $(window).resize(myResizeFunction).trigger('resize');
});

This will cause your resize handler to trigger on window resize and on document ready. Of course, you can attach your resize handler outside of the document ready handler if you want .trigger('resize')to run on page load instead.

这将导致您的调整大小处理程序在窗口调整大小和文档准备就绪时触发。当然,如果您想.trigger('resize')在页面加载时运行,您可以将调整大小处理程序附加到文档就绪处理程序之外。

UPDATE: Here's another option if you don't want to make use of any other third-party libraries.

更新:如果您不想使用任何其他第三方库,这是另一种选择。

This technique adds a specific class to your target element so you have the advantage of controlling the styling through CSS only (and avoiding inline styling).

这种技术为您的目标元素添加了一个特定的类,因此您可以仅通过 CSS 控制样式(并避免内联样式)。

It also ensures that the class is only added or removed when the actual threshold point is triggered and not on each and every resize. It will fire at onethreshold point only: when the heightchanges from <= 818 to > 819 or vice versa and not multiple times within each region. It's not concerned with any change in width.

它还确保仅在触发实际阈值点时添加或删除类,而不是在每次调整大小时添加或删除。它只会在一个阈值点触发:当高度从 <= 818 变为 > 819 或反之亦然,而不是在每个区域内多次。它不关心width 的任何变化。

function myResizeFunction() {
  var $window = $(this),
      height = Math.ceil($window.height()),
      previousHeight = $window.data('previousHeight');

  if (height !== previousHeight) {
    if (height < 819)
      previousHeight >= 819 && $('.footer').removeClass('hgte819');
    else if (!previousHeight || previousHeight < 819)
      $('.footer').addClass('hgte819');

    $window.data('previousHeight', height);
  }
}

$(function() {
  $(window).on('resize.optionalNamespace', myResizeFunction).triggerHandler('resize.optionalNamespace');
});

As an example, you might have the following as some of your CSS rules:

例如,您可能有以下一些 CSS 规则:

.footer {
  bottom: auto;
  left: auto;
  position: static;
}

.footer.hgte819 {
  bottom: 3px;
  left: 0;
  position: absolute;
}

回答by vivek

Use this:

用这个:

window.onresize = function(event) {
    ...
}

回答by Billy Moon

You can bind resizeusing .resize()and run your code when the browser is resized. You need to also add an elsecondition to your ifstatement so that your css values toggle the old and the new, rather than just setting the new.

您可以在调整浏览器大小时resize使用绑定.resize()并运行您的代码。您还需要在else您的if语句中添加一个条件,以便您的 css 值切换旧的和新的,而不仅仅是设置新的。