javascript 获取当前浏览器窗口中心

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7003906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:39:40  来源:igfitidea点击:

Get the current browser window center

javascriptjquery

提问by BiberFiver

How do I get the browser window height so I can find the center position?

如何获取浏览器窗口高度以便找到中心位置?

I only need the window height, not the web page height.

我只需要窗口高度,而不是网页高度。

I tried $(window).height() / 2but it only works if the browser has focus from the top of the page. If I scroll down I get the wrong center.

我试过了,$(window).height() / 2但只有当浏览器从页面顶部获得焦点时才有效。如果我向下滚动,我会得到错误的中心。

回答by Benjamin Atkin

To get the y value of the center of the current viewable area, use:

要获取当前可视区域中心的 y 值,请使用:

$(window).scrollTop() + $(window).height() / 2

I tried it on this page, by opening up the Web Inspector and entering:

我在这个页面上尝试过,打开 Web Inspector 并输入:

$('<p>').text('test').appendTo('body').css({position: 'absolute', top: $(window).scrollTop() + $(window).height() / 2});

回答by kirb

I think that the body's height needs to be in brackets for it to work properly:

我认为身体的高度需要在括号中才能正常工作:

var center = $("body").scrollTop() + ($("body").height() / 2);

However, if you're making a popup dialog, it's better to detect if the user is not on a mobile device then use the CSS "position: fixed". You detect for mobile devices because Mobile Safari doesn't understand fixed positioning in iOS versions before 5. Use this code for the detection:

但是,如果您正在制作弹出对话框,最好先检测用户是否在移动设备上,然后使用 CSS“位置:固定”。您检测移动设备是因为 Mobile Safari 在 5 之前的 iOS 版本中不理解固定定位。使用此代码进行检测:

var isMobile = navigator.appVersion.indexOf("Mobile/") != -1;

Ad@m

广告@m

回答by Lumi

Try window.outerHeightand window.outerWidth, which works in FF5 (and possibly earlier versions) and Chrome, but not in IE9. From googling it seems that this bit of info is not easy to get by in IE.

尝试window.outerHeightwindow.outerWidth,它适用于 FF5(可能还有更早的版本)和 Chrome,但不适用于 IE9。从谷歌搜索来看,这些信息在 IE 中并不容易获得。

Also see this other question dealing with IE.

另请参阅处理 IE 的其他问题