用户调整窗口大小后获取浏览器宽度和高度
在用户调整窗口大小后,有没有办法获得浏览器的宽度和高度。 例如,如果窗口是1920 x 1080并且用户将窗口更改为500乘500,那么有没有办法在JavaScript或jquery中获取这两个新值?
纯Javascript答案:
var onresize = function() { //your code here //this is just an example width = document.body.clientWidth; height = document.body.clientHeight; } window.addEventListener("resize", onresize);
这适用于chrome。 但是,它仅适用于chrome。 稍微跨浏览器的示例是使用事件目标属性“outerWidth”和“outerHeight”,因为在这种情况下,事件“target”是窗口本身。 代码就是这样的
var onresize = function(e) { //note i need to pass the event as an argument to the function width = e.target.outerWidth; height = e.target.outerHeight; } window.addEventListener("resize", onresize);
这在firefox和chrome中运行良好
希望能帮助到你 :)
编辑:在ie9测试,这也工作:)
您可以使用JQuery resize()函数。 还要确保添加相同的resize逻辑以重新加载事件。 如果用户在大小的窗口中重新加载,您的逻辑将无法工作。
$(window).resize(function() { $windowWidth = $(window).width(); $windowHeight = $(window).height(); }); $(document).ready(function() { //same logic that you use in the resize... });
通过收听resize
事件可以实现。
$(window).resize(function() { var width = $(window).width(); var height = $(window).height(); })
实际上,我使用它并且它对我有很大的帮助:
var TO = false; var resizeEvent = 'onorientationchange' in window ? 'orientationchange' : 'resize'; $(window).bind(resizeEvent, function() { TO && clearTimeout(TO); TO = setTimeout(resizeBody, 200); }); function resizeBody(){ var height = window.innerHeight || $(window).height(); var width = window.innerWidth || $(window).width(); alert(height); alert(width); }
您可以使用resize
事件以及height()
和width()
属性
$(window).resize(function(){ var height = $(window).height(); var width = $(window).width(); });
在这里查看更多示例
使用jQuery resize方法来监听窗口大小的变化。 在回调内你可以获得高度和宽度。
$(window).resize(function(){ var width = $(window).width(); var height = $(window).height(); });
如果你需要知道这些值来进行布局调整,我打赌你打算听这些值。 我建议使用Window.matchmedia()
API来实现此目的。
它的性能更高 ,基本上是JS媒体查询的JS等价物。
非常快速的使用示例:
if (window.matchMedia("(max-width: 500px)").matches) { /* the viewport is less than or exactly 500 pixels wide */ } else { /* the viewport is more than 500 pixels wide */ }
您还可以设置一个侦听器,每次matches
属性的状态更改时都会调用该侦听器。
有关使用侦听器的 说明和示例,请参阅MDN。