简体   繁体   English

如何通过Javascript获取窗口宽度

[英]How to get window width via Javascript

I am looking for some help concerning my Jquery. 我正在寻找关于我的Jquery的一些帮助。 I have an animation, that is opening a navigation menu, running from the right window site into the middle. 我有一个动画,即打开导航菜单,从右侧窗口站点运行到中间。 What I want to do now is: When the user is reducing the browser window width (lets say in a step of 100px), the Animation should run a 100px less into the middle. 我现在要做的是:当用户缩小浏览器窗口宽度时(比如100px的步长),动画应该减少100px到中间。 Below you can the the short version of my code. 您可以在下面找到我的代码的简短版本。 Is there a way to define the width using the value of a class, that I have written in my css? 有没有办法用我在css中写的类的值来定义宽度?

$(".slide-left").click(function(){
            $("#navibox").animate({ width: 863 }); });

You cannot define the width with the value in a class. 您无法使用类中的值定义宽度。 Although to get the width of the window itself, you can use 虽然要获得窗口本身的宽度,但您可以使用

window.innerWidth window.innerWidth

If you'd like to have some code run when you resize you can add an eventListener, with the event name of 'resize' like this. 如果您希望在调整大小时运行某些代码,则可以添加eventListener,事件名称为“resize”,如下所示。

window.addEventListener('resize', (e)=>{}) window.addEventListener('resize',(e)=> {})

The event passed from that callback has the property 'target' which is the window instance that you can grab the innerWidth from again. 从该回调传递的事件具有属性“target”,该属性是可以再次获取innerWidth的窗口实例。

If you have to update the animation with some new evaluated width, you can do it there. 如果您必须使用一些新的评估宽度更新动画,则可以在那里进行。

Thanks! 谢谢! I already tried something like this: 我已经尝试过这样的事:

$(window).resize(function(){
if ($(window).width() > 1000) { mywidth = 863; }
if ($(window).width() < 1001 && $(window).width() > 959 ) { mywidth = 823; }
if ($(window).width() < 960) { mywidth = 783; }
});```

In the animation I used:

```$("#navibox").animate({ mywidth });```

But that did not work...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM