Change Font Size dynamically based on Character count

心已入冬 提交于 2019-12-12 06:28:07

问题


I'm trying to adjust title sizes depending on character length. (wordpress)

This is what I have so far. It doesn't return any error but it doesn't work.

jQuery(function ($) {
    $(window).load(function () {
        var textLength = $('.autotitle').val().length;
        if (textLength < 20) {
            // Do noting 
        } else if (textLength > 20) {
            $('.autotitle').css('font-size', '16px');
        }
    });
});

回答1:


Many times one would like to decrease font size (make it smaller) when text is long based on letter count (text might have been entered through some CMS or translated text)

http://jsfiddle.net/jfbrLjt2/

 $('.text').each(function(){
     var el= $(this);
       var textLength = el.html().length;
        if (textLength > 20) {
            el.css('font-size', '0.8em');
        }
});



回答2:


 <span style="font-size:1vw;">test</span>

1vw stands for 1% of viewport width -great for responisve designs.

check this out: http://css-tricks.com/viewport-sized-typography/




回答3:


try this,Demo use html instead of using val

       var textLength = $('.autotitle').html().length;



回答4:


solved it with a php function

function trim_title() {
$title = get_the_title();
$limit = "14";

if(strlen($title) <= $limit) {
echo $title;
} else {
echo '<span class="longtitle">'; echo $title; echo '</span>';
}
}

thanks to everyone.




回答5:


If u use .autotitle then changes will be applied to every element where u use .autotitle as class attribute ...

Instead that u can use id attribute of particular element to apply changes to only that element

Ex :

$('#id').css('font-size','16px');



来源:https://stackoverflow.com/questions/24736701/change-font-size-dynamically-based-on-character-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!