我有一个元素,需要它的宽度不带(!)垂直滚动条。
Firebug告诉我车身宽度是1280px。
这两种方法在Firefox中都可以很好地工作:
console.log($('.element').outerWidth() );
console.log($('.element').outerWidth(true) );
$detour = $('.child-of-element').offsetParent();
console.log( $detour.innerWidth() );
它们都返回1263px,这就是我要查找的值。
然而,所有其他浏览器给我的1280px。
有没有一种跨浏览器的方法可以在没有(!)的情况下获得全屏宽度?垂直滚动条?
发布于 2014-08-14 08:46:21
您可以通过简单地编写以下代码来使用vanilla javascript:
var width = el.clientWidth;
您还可以使用它来获取文档的宽度,如下所示:
var docWidth = document.documentElement.clientWidth || document.body.clientWidth;
来源:MDN
您还可以获取整个窗口的宽度,包括滚动条,如下所示:
var fullWidth = window.innerWidth;
然而,并不是所有的浏览器都支持这一点,因此作为后备,您可能希望像上面那样使用docWidth
,并在scrollbar width上添加。
来源:MDN
发布于 2013-02-27 20:58:06
以下是一些假设$element
是jQuery
元素的示例:
// Element width including overflow (scrollbar)
$element[0].offsetWidth; // 1280 in your case
// Element width excluding overflow (scrollbar)
$element[0].clientWidth; // 1280 - scrollbarWidth
// Scrollbar width
$element[0].offsetWidth - $element[0].clientWidth; // 0 if no scrollbar
发布于 2014-06-10 17:50:53
试试这个:
$('body, html').css('overflow', 'hidden');
var screenWidth1 = $(window).width();
$('body, html').css('overflow', 'visible');
var screenWidth2 = $(window).width();
alert(screenWidth1); // Gives the screenwith without scrollbar
alert(screenWidth2); // Gives the screenwith including scrollbar
你可以通过使用下面的代码来获得屏幕宽度,无论有没有滚动条。在这里,我更改了body
的overflow值,并获得了包含和不包含滚动条的宽度。
https://stackoverflow.com/questions/8339377
复制相似问题