javascript - 动态地使子容器在可变宽度父容器中获取可用宽度

标签 javascript css dynamic truncate

我有一个包裹三个 float 容器的容器,包裹容器的宽度可变,最左边的内部容器的宽度为 100px,最右边的内部容器 code> 的宽度为 500px。 center container 没有设置宽度,但应尽可能多地占用剩余空间。

<style type="text/css">
    #outerContainer div:nth-child(1) {float: left; width: 100px}
    #outerContainer div:nth-child(2) {float: left}
    #outerContainer div:nth-child(3) {float: right; width: 500px}
</style>

<div id="outerContainer">
    <div>left most inner container</div>
    <div>center container</div>
    <div>right most inner container</div>
</div>

动态中心容器应用了一些样式,使其内容溢出:隐藏和省略号以供展示。

<style type="text/css">
#outerContainer div:nth-child(1) {
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
}
</style>

我不确定仅使用 css 动态缩放此内部元素宽度的解决方案是什么。这是我的有效 JavaScript 解决方案,但我想删除它,因为它看起来太多了。

NS.textWidth = function(sourceSel){
    var sourceSel = sourceSel,
        html_org = $(sourceSel).html(),
        html_calc = '<span>' + html_org + '</span>';

    //Wrap contents with a span.
    $(sourceSel).html(html_calc).css({width:'100%'});
    //Find width of contents within span.
    var width = $(sourceSel).find('span:first').width();

    //Replace with original contents.
    $(sourceSel).html(html_org);

    return width;
};

adjustContainerWidth();

$(window).bind('resize', function(e){
    clearTimeout(c.resize_timeout);

    c.resize_timeout = setTimeout(function() {
        adjustContainerWidth();
    }, 200);
});

function adjustContainerWidth() {
    var winW = parseInt($(window).width());
    var firstContainer = parseInt($('#outerContainer div:nth-child(1)').width());
    var lastContainer = parseInt($('#outerContainer div:nth-child(3)').width());
    var availW = winW - firstContainer - lastContainer;
    var textW = NS.textWidth('#outerContainer div:nth-child(2)');

    if (availW > 40 && availW < textW) {
        $('#outerContainer div:nth-child(1)').css({ width : availW + 'px' });
    } else {
        $('#outerContainer div:nth-child(1)').css({ width : textW + 'px' });
    }
}

最佳答案

关于javascript - 动态地使子容器在可变宽度父容器中获取可用宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10288401/

相关文章:

javascript - 找不到 'source-map' 的类型定义文件

javascript - Nashorn 绑定(bind)问题

c - 动态分配 C 数组的大小不应该出错吗?

jquery - 更改了 HTML,现在在each() 中无法访问子输入

javascript - Node : how to access json key that is a filename with dot

javascript - 需要 JavaScript 支持的网页抓取网站

html - 为什么 100vh 不能填满整个页面?

html - 在自动填充容器中居中网格元素

css - Chrome 中的 Rails 布局错误,但 Firefox 显示正常

java - 使用通用父类型输入参数强制执行动态多态调用