设置max-width后如何获取div的实际宽度? [英] How to get actual width of div when max-width is set?
本文介绍了设置max-width后如何获取div的实际宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个div,其中的某些文本具有max-width
值,并且需要一个display:block
.如何使用jQuery获取实际的width
?
I have a div with some text which has a max-width
value and it needs a display:block
. How can i get the actual width
using jQuery?
<style type="text/css">div{display:block; max-width:600px}</style>
<div>hello world</div>
当前,当值应该低得多时,它将返回600
.
Currently this returns 600
when the value should be much lower.
var ww = $('div').width(); // innerWidth() returns same value
推荐答案
尝试使用此代码.
$.fn.textWidth = function(){
var html_org = $(this).html();
var html_calc = '<span>' + html_org + '</span>';
$(this).html(html_calc);
var width = $(this).find('span:first').width();
$(this).html(html_org);
return width;
};
$("div").textWidth()
此函数将div的内容传递给时间范围,因为此元素是内联元素.它没有宽度或高度,因此其中的文本具有实际宽度.
This function passed the content of the div to a temporal span because this element is an inline element. It has no width or height, so the text inside them have the real width.
这篇关于设置max-width后如何获取div的实际宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文