javascript - 根据html长度调整字体大小

标签 javascript jquery css font-size

我知道有很多类似的帖子,但到目前为止我还没有能够解决这个问题。

上下文:
用户选择一个家,
房屋拥有独特的称号,
根据标题,调整字体大小以防止溢出

JS fiddle :https://jsfiddle.net/9uvpun5o/3/

$(function() {
    var that = $('#title'),
        planName = that.html().length
    ;
    // depending on html length, update font-size
    if(planName > 30) {
        that.css('font-size', '10px');
    } else if(planName > 20) {
        that.css('font-size', '12px');
    } else if(planName > 10) {
        that.css('font-size', '15px');
    }
});

字体根据 html 长度调整大小,但我需要它来响应。我尝试创建一个 .on("change") 事件,但未能正确实现。帮忙?

现在我只是从控制台更新标题,
$('#title').html("big long description thing");

但是,这将在未来通过从模态菜单中进行选择来完成。

最佳答案

编辑

好的,现在我明白了。那么你的 JS 应该是这样的:

$(function() {
    $('#title').on('DOMSubtreeModified', function() {
        var title = $('#title'),
            planName = title.html().length;

        // depending on html length, update font-size
        if(planName > 30) {
            title.css('font-size', '10px');
        } else if(planName > 20) {
            title.css('font-size', '12px');
        } else if(planName > 10) {
            title.css('font-size', '15px');
        }
    });

     $('li').on('click', function() {
         $('#title').text( $(this).text() );
     });
});

DOMSubtreeModified 应该在元素内容发生变化时触发(因为这会修改 DOM 子树)。 “点击”部分不是必需的,但出于测试目的我保留了它。

根据 DottoroOpera 不支持此事件,IE 9 及以下版本可能不支持或存在错误。

有关更多选项和信息,请检查这些其他 StackOverflow 问题:


按照您所说,用户将“选择一个单元”:

use case: User selects a unit, units have unique titles, depending on title, resize font to prevent overflow

因此,作为此操作的一部分,您需要更改字体大小。我用你的代码做了一个例子:

HTML

<ul>
    <li>On load, font size is set depending on length of title.</li>
    <li>However, I want this to be reactive...</li>
    <li>Change the length of Title and hit run</li>
    <li>Try clicking these itens</li>
    <li>You will see</li>
<ul>
<br/><br/>
<span id="title">TEST TEST</span><br/>

JS

$(function() {
    $('li').on('click', function() {
       var titleEl = $('#title').text( $(this).text() ),
           planName = titleEl.text().length;

        // depending on text length, update font-size
        if (planName > 30) {
            titleEl.css('font-size', '10px');
        } else if (planName > 20) {
            titleEl.css('font-size', '12px');
        } else if(planName > 10) {
            titleEl.css ('font-size', '15px');
        } 
    });
});

尝试点击列表中的元素。你看?作为对“更改单位”的响应,标题和字体大小发生变化。

如果此答案对您没有帮助,请提供更多详细信息。

关于javascript - 根据html长度调整字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30808653/

相关文章:

javascript - Vuejs 是否具有与 jQuery 类似的 API 来远程异步 http 调用(Ajax)?

html - 基本 HTML/CSS - 边距和显示行为

css - 在位置为 :fixed elements 的 Safari 7 上滚动时,部分页面不可见

html - Bootstrap-framework - col-sm - 小屏幕网格不起作用

javascript - 根据url滚动网页

jquery - 你如何在对话框中打开一个 URL JQUERY UI

javascript - CF-Hash 属性和脚本神秘地添加到 mailto 链接

javascript - 在 Javascript 中传递 (laravel) 数组

javascript - 如何创建返回页面顶部的按钮?

javascript - 让数据等待 JavaScript 上变量的声明完成?