javascript - 根据文本长度动态更改元素的高度

标签 javascript jquery css

我正在使用 cordova 和 jquery mobile,我正在开发一个可以发送通知的应用程序。在通知面板中,我显示所有收到的通知。

所以那个通知的 html 标记是这样的:

 for(var count = 0; count < info.data.length; count++){
    var shortmessage = info.data[count][3];
    var category = info.data[count][4];
    var typeOf = info.data[count][5];
    var style = '';

    if(typeOf === "warning"){
        imgPath = 'img/icons/alarm.png';
    } else {
        imgPath = 'img/icons/alert.png';
    }

    console.log(shortmessage, shortmessage.length);

     // if long message, set the style
    if ( shortmessage.length > 40 ){
        style = 'min-height: 70px';
    }else if ( shortmessage.length > 65 ){
        style = 'min-height: 80px !important';
    }else if ( shortmessage.length > 75 ){
        style = 'min-height: 100px !important';
    }

if (category === 'vertrek'){
               departureHtml = `
                ${departureHtml}
                <div class='notification-item' style='${style}'>
                    <div class='ui-grid-a notification-grid'>
                        <div class='ui-block-a'>
                            <img class='notification-image' src='${imgPath}'>
                        </div>
                        <div class='ui-block-b'>
                            <span class='notification-text'>${shortmessage}</span>
                        </div>
                    </div>
                </div>`;

            $('.departure-notification-append').empty().prepend(departureHtml);
        }

        if (category === 'inchecken'){
            incheckHtml = `
                ${incheckHtml}
                <div class='notification-item' style='${style}'>
                    <div class='ui-grid-a notification-grid'>
                        <div class='ui-block-a'>
                            <img class='notification-image' src='${imgPath}'>
                        </div>
                        <div class='ui-block-b'>
                            <span class='notification-text'>${shortmessage}</span>
                        </div>
                    </div>
                </div>`;

            $('.check-in-notification-append').empty().prepend(incheckHtml);
        }

这是 5 个类别中的两个,但它似乎比将 70px 的高度 分配给所有 notification-items 大于 40。 但它不会改变大于 65 和 75 的消息的高度。

所以我的问题是如何根据 notification-text 中的文本动态设置 notification-item 的高度

最佳答案

设置 height: auto 将允许元素动态调整大小以占据呈现其内容所需的任何高度。

我会使用填充来实现额外的高度操作,而不是使用高度属性。

关于javascript - 根据文本长度动态更改元素的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41511718/

相关文章:

javascript - 更简单的 Javascript 计数器

jquery - 隐藏div时如何设置背景颜色

javascript - 移动导航在 Safari 上无法正常工作

javascript - 向表单添加字段 (jQuery)

javascript - 如果滚动条可见,则滚动内容

javascript - Firefox 操作系统按键与 jQuery

javascript - 如何使用 jQuery 添加通用页眉页脚

jquery - 我们如何处理 "checking for new versions of a page"?

html - 如何创建文本框六边形边框?

javascript - 将效果淡入 Bootstrap 3 轮播