找到使用 jQuery 完整显示项目所需的最小宽度?
有没有可能找到完整显示一个div所需的像素数?
现在,我的 div 为 100%,但我真的希望它与内容一样小......(不能使用浮动或其他 css 技巧)。
Is it possible to find the number of pixels that is required to display a div completely?
Right now, my div is at 100%, but I would really like it to be as small as the content... (can't use floats or other css tricks).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个问题可能取决于内容,因此在没有看到您的 HTML 的情况下,我们只能猜测,但 div 根据其内容调整自身大小的唯一方法是当它的
position:absolute
时。因此,您可以使用这样的函数来让 div 暂时换行到其内容,以便您可以测量内容宽度。然后,如果需要,您可以使用该宽度来设置其大小:
您可以在此处看到它的工作原理: http://jsfiddle.net/jfriend00/ L2J5w/
仅供参考,我从 jQuery 学到了这项技术。它在内部使用它来测量某些东西的宽度。它甚至有一个名为
.swap()
的内部(未记录)函数,用于保存一组 CSS 属性的值,将这些 CSS 属性设置为其他内容,进行测量,然后将 CSS 属性恢复为其原始值。This question may be dependent upon the content so without seeing your HTML, we can only guess, but the only way that a div sizes itself to it's content is when it's
position: absolute
.So, you can use a function like this to get a div to temporarily wrap to it's content so you can measure the content width. You would then use that width to set it's size if you wanted:
You can see it work here: http://jsfiddle.net/jfriend00/L2J5w/
FYI, I learned this technique from jQuery. It uses it internally to measure the width of some things. It even has an internal (non-documented) function called
.swap()
that is used for saving the values of a set of CSS properties, setting those CSS properties to something else, taking a measurement, then restoring the CSS properties to their original values.如果您没有将
div
宽度设置为 100% 并设置display: inline
,那么只要不溢出,它应该只占用与内容一样多的空间。如果内容确实溢出,这将告诉您当存在滚动条时 div 内容的宽度
If you do not set the
div
width to 100% and set thedisplay: inline
, then it should only take as much space as the content as long as it does not overflow.If the contents do overflow then, this will tell you the width of the div for its contents when a scrollbar is present