gpt4 book ai didi

jquery - 如何在没有滚动条的情况下获取jquery中元素的innerWidth

转载 作者:行者123 更新时间:2023-12-03 22:34:41 27 4
gpt4 key购买 nike

给定一个带有滚动条的div(例如overflow:auto的b/c),如何获得元素的准确innerWidth?在我的示例中:http://jsfiddle.net/forgetcolor/2J7NJ/ width 和innerWidth 报告相同的宽度。我想要的数字应该小于 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());​

更新:

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

最佳答案

通过将新的 DIV 插入到 #box1-Container 中,该 DIV 将获得可用宽度 - 读取其宽度会返回一个看似正确的值。

HTML 和 CSS 均保持不变

JS 变成了

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

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

我还 fork 了你的 Fiddle 来看看我做了什么:http://jsfiddle.net/xc9xQ/2/

因此,要使用函数获取该值:

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 - 如何在没有滚动条的情况下获取jquery中元素的innerWidth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10692598/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com