Div智能宽度 [英] Div smart width

查看:104
本文介绍了Div智能宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看小提示

<div class="e" style="left:5px;top:5px;">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbb</div>

<div class="e" style="left:5px;top:100px;">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div>​



css



css

.e {
    font-size: 10px;
    font-family: arial;
    background-color: yellow;
    position: absolute;
    max-width: 300px;
}

你会注意到第二个div适合内容的大小,第一个div有一堆空的空间在a和b的右边。这是因为div的最大宽度为300px,然后将b包装到第二行。包装是好的,但我会期望div然后收缩回到a的宽度,以便没有空的空间在右边。

you will notice the 2nd div fits the size of the content exactly, but on the first div there's a bunch of empty space to the right of the a's and b's. This is because the div hit its max width of 300px and then wrapped the b's to a 2nd line. The wrapping is good, but then I would expect the div to then shrink back down to the width of the a's so that there's no empty space to the right.

可以让它这样做吗?

在Chrome和FF中测试。

Tested in Chrome and FF. ​

推荐答案

要将div(或任何元素)缩小到其文本内容的大小, JavaScript获取包含其内容并使用 range.getBoundingClientRect()获取范围大小的范围

To shrink a div (or any element) to the size of its text content, you can use JavaScript to get a range that contains its contents and get the size of the range using range.getBoundingClientRect():

function sizeElementToContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var textRect = range.getBoundingClientRect();
    el.style.width = textRect.width + "px";
}

但是,这当然只适用于Modern浏览器。 IE8和IE7有不同的方法处理范围。实际上,IE7自动处理 max-width 的方式,但是当我们的IE8代码运行以重新调整IE7的divs时,它将divs缩小为0为避免为特定浏览器版本编写代码,此代码运行在IE7和IE8上,但包含一些额外的逻辑,因此它可以在两个浏览器版本上工作:

But, of course, that only works with Modern browsers. IE8 and IE7 have different methods for working with ranges. Actually, IE7 automatically handles max-width the way you want it to, but when our IE8 code is run to re-size the divs on IE7, it shrinks the divs to 0. To avoid writing code for specific browser versions, this code runs on IE7 and IE8, but includes a little extra logic so that it works on both browser versions:

function sizeElementToContents(el) {
    var range, width;
    if (document.createRange) {
        range = document.createRange();
        range.selectNodeContents(el);
        width = range.getBoundingClientRect().width;
    }
    else {
        range = document.body.createTextRange();
        range.moveToElementText(el);
        range.moveStart("character", 1);
        width = range.boundingWidth;
        var height = range.boundingHeight;
        range.collapse();
        range.moveEnd("character", 1);
        if (range.boundingHeight == height) {
            return; // text doesn't wrap, so don't resize
        }
    }
    el.style.width = width + "px";
}

工作演示 http://jsfiddle.net/gilly3/HZRFb/

这篇关于Div智能宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆