如何在 JavaScript 中触发窗口大小调整事件?
我已经在窗口调整大小时注册了触发器。我想知道如何触发要调用的事件。例如,当隐藏一个 div 时,我希望调用我的触发函数。
我发现window.resizeTo()
可以触发该函数,但是还有其他解决方案吗?
I have registered a trigger on window resize. I want to know how I can trigger the event to be called. For example, when hide a div, I want my trigger function to be called.
I found window.resizeTo()
can trigger the function, but is there any other solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
在可能的情况下,我更喜欢调用函数而不是调度事件。如果您可以控制要运行的代码,那么这种方法很有效,但如果您不拥有该代码,请参阅下文。
在此示例中,您可以调用
doALoadOfStuff
函数而不分派事件。在现代浏览器中,您可以使用触发事件 :
这在 Internet Explorer 中不起作用,您必须手动操作:
jQuery 有
触发
方法,其工作原理如下:并且有一个警告:
您还可以模拟特定元素上的事件...
Where possible, I prefer to call the function rather than dispatch an event. This works well if you have control over the code you want to run, but see below for cases where you don't own the code.
In this example, you can call the
doALoadOfStuff
function without dispatching an event.In your modern browsers, you can trigger the event using:
This doesn't work in Internet Explorer, where you'll have to do the longhand:
jQuery has the
trigger
method, which works like this:And has the caveat:
You can also simulate events on a specific element...
使用jQuery,你可以尝试调用trigger:
With jQuery, you can try to call trigger:
结合 pomber 和 avetisk 的答案以覆盖所有浏览器并且不会引起警告:
Combining pomber's and avetisk's answers to cover all browsers and not causing warnings:
也适用于 IE 的纯 JS(来自 @Manfred评论)
或者对于角度:
A pure JS that also works on IE (from @Manfred comment)
Or for angular:
我实际上无法让它与上述任何解决方案一起使用。一旦我用 jQuery 绑定了事件,它就可以正常工作,如下所示:
I wasn't actually able to get this to work with any of the above solutions. Once I bound the event with jQuery then it worked fine as below:
这就是
我所用的...除非我误解了你的要求。
just
is what I use... unless I misunderstand what you're asking for.
我相信这应该适用于所有浏览器:
I believe this should work for all browsers:
用 RxJS 响应
说像 Angular 中的东西
如果需要手动订阅(或者不是 Angular),
因为我的初始 startWith 值可能不正确(调度以进行更正)
在 Angular 中(我可以..)
Response with RxJS
Say Like something in Angular
If manual subscription desired (Or Not Angular)
Since my intial startWith Value might be incorrect (dispatch for correction)
In say Angular (I could..)
window.resizeBy()
会触发window的onresize事件。这适用于 Javascript 或 VBScript。window.resizeBy(xDelta, yDelta)
调用类似于window.resizeBy(-200, -200)
将页面缩小 200px x 200px。window.resizeBy()
will trigger window's onresize event. This works in both Javascript or VBScript.window.resizeBy(xDelta, yDelta)
called likewindow.resizeBy(-200, -200)
to shrink page 200px by 200px.