开发者

Getting Chrome browser width (IGNORING Scrollbars)

开发者 https://www.devze.com 2023-03-19 07:06 出处:网络
I need the width of the Chrome browser window and my current code is: $(\"input#myHiddenValue\").val($(window).width());

I need the width of the Chrome browser window and my current code is:

$("input#myHiddenValue").val($(window).width());

I call this from a开发者_高级运维 page which has a scrollbar, but I need it to be the full width of the Chrome browser without a scroll bar.

Can anyone help?


Check out:

window.screen.availWidth

I found this in a doc: Returns the amount of horizontal space in pixels available to the window.

And it is larger than my ? this.width`.


Can't you just add on 15px to make it right?


try this

$("input#myHiddenValue").val($(body).width());


While the window.screen.availWidth is good for some, it doesn't solve the core problem of being able to get an accurate number of the right browser width and is unreliable because you never know whether someone's going to be running it in a window smaller than their screen.

Unfortunately I've not been able to find a good way of getting it, so here's a bit of a hacky way of doing it that works for me and might help others out:

CSS:

.no-scroll{ overflow:hidden; }

JS (Assuming jQuery):

$('body').addClass('no-scroll');
var accurateWindowWidth = $(window).width();
$('body').removeClass('no-scroll');

Basically, you're hiding the scrollbar for a split second while you calculate the width of the page by disallowing the page to scroll - This works well in Chrome for me, without a noticeable jump, but obviously your mileage may very depending on your machine's speed and stuff.

0

精彩评论

暂无评论...
验证码 换一张
取 消