为什么我的jQuery不响应窗口大小调整? [英] Why doesn't my jQuery respond to window resize?
问题描述
我正在使用jQuery在页面转换中添加一些元素(通过 jQuery Transit 插件)当徘徊时。由于我正在尝试响应式设计,我希望这些转换仅在浏览器具有特定大小或更大时发生。
I'm using jQuery to add some make some elements on a page transition (via the jQuery Transit plugin) when hovered upon. Since I'm trying to design responsively, I want these transitions to only happen when the browser is a certain size or larger.
我已将以下代码编写为尝试这样做:
I've written the following code as an attempt to do this:
$(document).ready(function(){
var $window = $(window);
var $logo = $('.logo');
function checkWidth() {
windowsize = $window.width();
}
checkWidth();
$(window).resize(checkWidth);
if (windowsize >= 768) {
$logo.hoverIntent(
function(){
$logo.transition({
perspective: '600px',
rotateY: '-10deg'
});
},
function(){
$logo.transition({
perspective: '600px',
rotateY: '0deg'
});
}
);
}
});
如果我在大型浏览器中加载页面,它会按预期工作 - 悬停效果处于活动状态。如果我调整浏览器的大小,使其缩小(超过断点)并刷新,则可以正常工作 - 禁用悬停效果。但是如果我在没有刷新的情况下调整窗口大小,那么效果就不会响应 - 它会保持禁用状态(如果从小屏幕大屏幕调整到大屏幕)或者活动(如果从大到小调整大小)。
If I load the page in a large browser, it works as expected--the hover effect is active. If I resize the browser, making it smaller (past the breakpoint) and refresh, then it works--the hover effect is disabled. But if I resize the window without refreshing in between, then the effect doesn't respond--it either remains disabled (if resizing from a small to a large screen) or active (if resizing from large to small).
当然,这是一个小小的怪癖,但我无法弄清楚为什么会发生这种情况。据我所知,当窗口调整大小时,应该更新 windowsize
变量,应该是检查 if
语句。我忽略了什么使得情况并非如此?
It's a minor quirk, to be sure, but I can't exactly figure out why it's happening. As far as I can tell, when the window resizes, it should be updating the windowsize
variable, which should be checked in the if
statement. What am I overlooking that makes this not the case?
非常感谢。
推荐答案
所有 checkWidth
目前所做的是为 windowsize
赋值。您需要将实际读取 windowsize
的代码移动到 checkWidth
。
All checkWidth
currently does is assign a value to windowsize
. You need to move the code that actually reads windowsize
into checkWidth
.
$(document).ready(function(){
var $window = $(window);
var $logo = $('.logo');
function checkWidth() {
windowsize = $window.width();
if (windowsize >= 768) {
$logo.hoverIntent(
function(){
$logo.transition({
perspective: '600px',
rotateY: '-10deg'
});
},
function(){
$logo.transition({
perspective: '600px',
rotateY: '0deg'
});
}
);
}
}
// can trigger the resize handler instead of
// explicitly calling checkWidth()
$(window).resize(checkWidth).resize();
});
这篇关于为什么我的jQuery不响应窗口大小调整?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!