我有一个元素,需要它的宽度没有(!)垂直滚动条。
Firebug告诉我体宽是1280px。
其中任何一种在Firefox中运行良好:
console.log($('.element').outerWidth() );
console.log($('.element').outerWidth(true) );
$detour = $('.child-of-element').offsetParent();
console.log( $detour.innerWidth() );
他们都返回 1263px ,这是我正在寻找的值。
但是所有其他浏览器都会给我 1280px 。
是否有跨浏览器的方式来获得没有(!)垂直滚动条的全屏宽度?
答案 0 :(得分:149)
.prop("clientWidth")
和.prop("scrollWidth")
var actualInnerWidth = $("body").prop("clientWidth"); // El. width minus scrollbar width
var actualInnerWidth = $("body").prop("scrollWidth"); // El. width minus scrollbar width
JavaScript :中的
var actualInnerWidth = document.body.clientWidth; // El. width minus scrollbar width
var actualInnerWidth = document.body.scrollWidth; // El. width minus scrollbar width
P.S:请注意,为了可靠地使用scrollWidth
,您的元素不应该水平溢出
<强> jsBin demo 强>
您也可以使用.innerWidth()
,但仅适用于body
元素
var innerWidth = $('body').innerWidth(); // Width PX minus scrollbar
答案 1 :(得分:30)
您只需编写以下内容即可使用vanilla javascript:
var width = el.clientWidth;
您也可以使用它来获取文档的宽度,如下所示:
var docWidth = document.documentElement.clientWidth || document.body.clientWidth;
来源:MDN
您还可以获得整个窗口的宽度,包括滚动条,如下所示:
var fullWidth = window.innerWidth;
但是并非所有浏览器都支持此功能,因此作为后备广告,您可能需要使用上述docWidth
,并添加scrollbar width。
来源:MDN
答案 2 :(得分:13)
以下是一些假设$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
答案 3 :(得分:8)
试试这个:
$('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
的溢出值,并使用和不使用滚动条获得宽度。
答案 4 :(得分:5)
在没有滚动条的情况下获得正确宽度和高度的最安全的地方来自HTML元素。试试这个:
var width = document.documentElement.clientWidth
var height = document.documentElement.clientHeight
浏览器支持相当不错,IE 9及以上支持。对于OLD IE,请使用此处提到的众多后备之一。
答案 5 :(得分:0)
我遇到了类似的问题,width:100%;
为我解决了这个问题。我在尝试了这个问题的答案之后得出了这个解决方案,并意识到<iframe>
的本质将使这些javascript测量工具不准确而不使用某些复杂的功能。 100%做是一种在iframe中处理它的简单方法。我不了解您的问题,因为我不确定您操作的HTML元素。
答案 6 :(得分:0)
这些解决方案都不适用于我,但我可以通过取宽度并减去width of the scroll bar来解决这个问题。我不确定这是跨浏览器的兼容性。
答案 7 :(得分:0)
这是我使用的
function windowSizes(){
var e = window,
a = 'inner';
if (!('innerWidth' in window)) {
a = 'client';
e = document.documentElement || document.body;
}
return {
width: e[a + 'Width'],
height: e[a + 'Height']
};
}
$(window).on('resize', function () {
console.log( windowSizes().width,windowSizes().height );
});