jQuery - 不可见时获取元素宽度(显示:无)似乎在jQuery中,当元素不可见时,width()返回0.有道理,但我需要获取表的宽度,以便在显示父级之前设置父级的宽度。如下所述,父母中有文本,使父母倾斜并且看起来很讨厌。我希望父级只有表格的宽度并且包含文本。<div id="parent">
Text here ... Can get very long and skew the parent <table> ... </table>
Text here too ... which is why I want to shrink the parent based on the table</div>CSS:#parent{
display: none;}使用Javascript:var tableWidth = $('#parent').children('table').outerWidth();if (tableWidth > $('#parent').width()){
$('#parent').width(tableWidth);}tableWidth总是返回0,因为它不可见(我猜是因为它在可见时给了我一个数字)。有没有办法获得表格的宽度而不使父母可见?
3 回答
湖上湖
TA贡献2003条经验 获得超2个赞
function realWidth(obj){
var clone = obj.clone();
clone.css("visibility","hidden");
$('body').append(clone);
var width = clone.outerWidth();
clone.remove();
return width;}realWidth($("#parent").find("table:first"));
阿晨1998
TA贡献2037条经验 获得超6个赞
根据罗伯茨的回答,这是我的功能。如果元素或其父元素已经通过jQuery淡出,这对我有用,可以获得内部或外部维度,也可以返回偏移值。
/ edit1:重写了这个函数。它现在变小了,可以直接在对象上调用
/ edit2:该函数现在将在原始元素而不是正文之后插入克隆,从而使克隆可以维护继承的维度。
$.fn.getRealDimensions = function (outer) {
var $this = $(this);
if ($this.length == 0) {
return false;
}
var $clone = $this.clone()
.show()
.css('visibility','hidden')
.insertAfter($this);
var result = {
width: (outer) ? $clone.outerWidth() : $clone.innerWidth(),
height: (outer) ? $clone.outerHeight() : $clone.innerHeight(),
offsetTop: $clone.offset().top,
offsetLeft: $clone.offset().left };
$clone.remove();
return result;}var dimensions = $('.hidden').getRealDimensions();- 3 回答
- 0 关注
- 840 浏览
添加回答
举报
0/150
提交
取消
