Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

width - how to get innerWidth of an element in jquery WITHOUT scrollbar

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:

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

Update:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 and CSS both remain unchanged

JS Becomes

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...