[英]How can I define a variable depending on the width of the screen?
I'm animating based on scroll position using TweenMax. 我正在使用TweenMax基于滚动位置进行动画处理。 The position at which I want to animate changes depending on the screen size. 我要设置动画的位置取决于屏幕尺寸。 Is it possible to have a variable change based on the width of the screen? 是否可以根据屏幕的宽度进行可变的更改?
I'm fairly new and using a lot of copy/paste solutions. 我是新手,并且使用了大量复制/粘贴解决方案。 I have two rectangular divs beside each other that flip over like cards to display information on the back. 我有两个彼此相邻的矩形div,它们像卡片一样翻转以在背面显示信息。 When viewed on a mobile screen, these cards stack vertically instead of beside each other. 在移动屏幕上查看时,这些卡垂直堆叠而不是彼此堆叠。 This then changes the point at which I want to animate the flipping of the card. 然后,这将更改我要为卡片翻转动画设置的点。
The solution I've landed on is to change var sceneStart depending on a media query. 我找到的解决方案是根据媒体查询更改var sceneStart。 This is just an idea for a solution to the problem. 这只是解决问题的一个想法。
This is what I have tried to no success. 这是我尝试没有成功的事情。
var sceneStart2;
if (window.matchMedia("(max-width: 480px)")) {
sceneStart2 = 3500
} else {
sceneStart2 = 2000
}
Expected result is on a large screen while divs are beside each other, card2 flips at 2000 but on a mobile screen card flips at 3500. 当div并排放置时,预期结果是在大屏幕上,card2在2000翻转,但在移动屏幕上card在3500翻转。
Actual result is that it breaks the flip entirely and doesn't function. 实际结果是它完全破坏了翻转并且无法正常工作。
You need to check the matches
property of the MediaQueryList
returned by matchMedia
: 您需要检查matches
的财产MediaQueryList
通过返回matchMedia
:
var sceneStart2; if (window.matchMedia("(max-width: 480px)").matches) { sceneStart2 = 3500 } else { sceneStart2 = 2000 } console.log(sceneStart2);
Check out this article on MDN for more info about matchMedia
. 在MDN上查看此文章,以获取有关matchMedia
更多信息。
If you want this to update when the window resizes, you could move this logic into a function that gets called initially and on every window resize event: 如果希望在调整窗口大小时更新此逻辑,则可以将此逻辑移到最初在每个窗口调整大小事件中调用的函数中:
var sceneStart2; calcSceneStart2(); window.addEventListener('resize', calcSceneStart2); function calcSceneStart2() { if (window.matchMedia("(max-width: 480px)").matches) { sceneStart2 = 3500 } else { sceneStart2 = 2000 } console.log(sceneStart2); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.