本文介绍了如何在没有滚动条的情况下获取jQuery中元素的innerWidth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个包含滚动条的div(例如b/c ofoverflow:auto),如何获取元素的精确innerWidth?在我的示例中: http://jsfiddle.net/forgetcolor/2J7NJ/ width和innerWidth报告相同宽度.我想要的数字应小于100.

Given a div that has a scrollbar in it (e.g. b/c of overflow:auto), how do I get the accurate innerWidth of the element? In my example: http://jsfiddle.net/forgetcolor/2J7NJ/ width and innerWidth report the same width. The number I want should be less than 100.

HTML:

<div id='box1'>
<div id='box2'>
</div>
</div>
<p id="w"></p>
<p id="iw"></p>​

CSS:

#box1 {
    width:100px;
    height:100px;
    overflow:auto;
}

#box2 {
    width:200px;
    height:200px;
    background-color:#aaa;
}

JavaScript:

Javascript:

$('#w').text("width is: "+$('#box1').width());
$('#iw').text("inner width is: "+$('#box1').innerWidth());​

更新:

当box2 div包含大图像时,我需要它工作(因此,需要一秒钟来加载).这是一个示例,无法集成下面的解决方案之一(Lukx'),该示例不起作用: http://jsfiddle.net/forgetcolor/rZSCg/1/.有什么想法如何让它在计算宽度之前等待图像加载?

I need this to work when the box2 div contains a large image (thus, takes a second to load). Here's an example, integrating one of the solutions below (Lukx'), that doesn't work: http://jsfiddle.net/forgetcolor/rZSCg/1/. Any ideas how to get it to wait for the image to load before calculating the width?

推荐答案

通过在#box1 -Container中插入新的DIV,此DIV将获得可用宽度-读取其宽度将返回一个看起来正确的值

By inserting a new DIV into the #box1-Container, this DIV will obtain the available width - and reading its width returns a value that appears to be correct.

HTML和CSS均保持不变

HTML and CSS both remain unchanged

JS成为

var helperDiv = $('<div />');
$('#box1').append(helperDiv);

$('#iw').text("inner width is: " + helperDiv.width());
helperDiv.remove();​​​​​​​​​​​​​​​​​​​​​​​​​​​ // because we dont need it anymore, do we?

我也分叉了您的小提琴,看看我做了什么: http://jsfiddle.net/xc9xQ/2 /

I also forked your Fiddle to see what I have done: http://jsfiddle.net/xc9xQ/2/

因此要通过函数获取该值:

So to get this value with a function:

function widthWithoutScrollbar(selector) {
  var tempDiv = $("<div/>");
  $(selector).append(tempDiv);
  var elemwidth = tempDiv.width();
  tempDiv.remove();
  return elemwidth;
};

//Example
console.log($('#page').width());  // 1280
console.log(widthWithoutScrollbar('#page'));  // 1265

这篇关于如何在没有滚动条的情况下获取jQuery中元素的innerWidth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 06:37