设置max-width时如何获得div的实际宽度?
我有一个带有一些文本的div,它有一个max-width
值,需要一个display:block
。 如何使用jQuery获取实际width
?
div{display:block; max-width:600px} hello world
目前,当值应该低得多时,返回600
。
var ww = $('div').width(); // innerWidth() returns same value
试试这个代码。
$.fn.textWidth = function(){ var html_org = $(this).html(); var html_calc = '' + html_org + ''; $(this).html(html_calc); var width = $(this).find('span:first').width(); $(this).html(html_org); return width; }; $("div").textWidth()
此函数将div的内容传递给时间跨度,因为此元素是内联元素。 它没有宽度或高度,因此它们内部的文本具有实际宽度。
默认情况下, div
元素会扩展到其容器的高度,但您可以尝试将display属性设置为inline-block
。
$(function() { $("#showWidthBtn").click(function() { alert($("div").width()); }); });
div { background: #eee; max-width: 500px; display: inline-block; }
Hello World!
正如其他人指出的那样,父容器的宽度是其子容器的上限。 此代码段显示红色父div中的子蓝色div。 虽然蓝色子项的最大宽度设置为1500,但其实际宽度由jquery捕获为$('.blue').width()
显示为1500以下。
$('#output').append($('.blue').width());
.blue { /* child */ max-width: 1500px; height: 100%; background-color: blue; } .red { /* parent */ background-color: red; height: 70px; padding: 7px; }
The blue width is bound by its red parent. Blue's width is now:
你快到了。 outerWidth()
做到了这一点: http : outerWidth()