使用窗口调整大小功能使变量保持最新? [英] Using the window resize function to keep variables uptodate?
问题描述
当调整窗口大小时,我对如何保持我创建的变量保持最新有些困惑,因此我的滚动功能会继续获取正确的值.基本上,我有多个元素,其中包含一条消息,当用户将元素滚动到视口高度的50%时会显示该消息.这可以正常工作,但是我的问题是当我调整大小时,我不确定如何更新变量boxHeight, elementOffset, verticalMatch
,该变量可以控制我在滚动事件中需要使用的值.我想知道有人可以帮忙解释一下我该如何解决吗?
I am a little confused on how to keep some variables Ive created uptodate when the window is resized so my scroll function carries on getting the correct values. Basically I have multiple elements that contain a message that gets displayed when the user scrolls the element into 50% height of the viewport height. This works fine but my issue is when I resize I'm not sure how to update my variables boxHeight, elementOffset, verticalMatch
which keep control of the values I need to use in my scroll event. I was wondering can someone help explain how I can resolve this?
我的代码如下
var windowHeight = $(window).height(),
headerHeight = $('.header').height();
$('.box').each(function (i,e) {
var el = $(e);
var boxHeight = el.height(),
elementOffset = el.offset().top,
verticalMatch = (windowHeight / 2) + (headerHeight / 2) - (boxHeight / 2);
$(window).on('scroll', function () {
var scrollTop = $(window).scrollTop(),
distance = elementOffset - scrollTop;
if( distance <= verticalMatch ) {
el.addClass('is-active');
}
});
});
$(window).on('resize', function() {
windowHeight = $(window).height()
elementOffset = $('.box').offset().top;
$('.box').each(function (i,e) {
var el = $(e);
//update boxHeight, elementOffset, verticalMatch
verticalMatch = (windowHeight / 2) + (headerHeight / 2) - (boxHeight / 2);
});
});
这是JS小提琴: http://jsfiddle.net/fm4z7/2/
如果有人可以解释我如何做到这一点,那就太好了!
If someone could explain how I do this it would be great!
推荐答案
如果您要做的只是在调整大小事件期间更新大小变量,请执行以下操作:
If all you want to do is update your sizing variables during a resize event, then do just that:
$(window).on('resize', function() {
windowHeight = $(window).height();
elementOffset = $('.box').offset().top;
});
您的变量是全局变量,因此可以在任何地方访问它们.
Your variables are global so they can be accessed anywhere.
这篇关于使用窗口调整大小功能使变量保持最新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!