jQuery在窗口调整大小 [英] jQuery on window resize
问题描述
我有以下JQuery代码:
I have the following JQuery code:
$(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 containerHeight
to also be checked when they are resizing the window?
任何想法?
推荐答案
下面是一个使用jQuery,javascript和css来处理大小调整事件的例子。
(css if you best bet bet if you 只是在调整大小(媒体查询)的样式化样式)
http://jsfiddle.net/CoryDanielson/LAF4G /
.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.
要调整调整大小的代码的频率,您可以使用调整大小的代码。 去抖或限幅方法从< a href =http://underscorejs.org/>下划线& lowdash 图书馆。
To limit how often your resize code is called, you can use the debounce or throttle methods from the underscore & lowdash libraries.
-
debounce
只会在LAST调整大小事件后的几毫秒内执行调整大小代码X.当用户调整浏览器大小后,您只想调用大小调整代码一次,这是理想的选择。 -
throttle
只会执行调整大小的动作,因此更新图表,图表和版面配置代码每X个毫秒。它调节代码被调用的频率。
debounce
will 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.throttle
will 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.
如果没有下划线或lowdash, ,你可以自己实现一个类似的解决方案:
JavaScript / JQuery:$(window).resize在调整大小完成后如何触发?
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?
这篇关于jQuery在窗口调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!