【问题标题】:Change Font Size dynamically based on Character count根据字符数动态更改字体大小
【发布时间】:2014-09-04 09:06:23
【问题描述】:

我正在尝试根据字符长度调整标题大小。 (wordpress)

这是我目前所拥有的。它不会返回任何错误,但它不起作用。

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

【问题讨论】:

  • 什么都不做为什么会有if条件..直接放else条件。
  • .autotitle 是什么 html 元素?如果不是input,请尝试.html() 而不是.val(),但请注意它可能包含内部标签和空格。
  • .autotitle 指的是一个类。我把它改成了这个。现在它会更改每个 .autotitle 类 div 而不计算字符
  • codejQuery(function ($) { $(window).load(function() { var textLength = $(".autotitle").val().length; if(textLength code
  • 实际上,它很重要并且可以工作,但是它将 css 应用于该类的所有元素。我怎样才能将其仅应用于适合计数的那些?

标签: jquery css count character string-length


【解决方案1】:

试试这个,Demo 使用 html 而不是使用 val

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

【讨论】:

  • .val 和 .html 现在都可以使用,但它会更改所有 .autotitle 元素,而不仅仅是适合计数的元素
  • 使用这个,$(".autotitle:first").html()
【解决方案2】:

用php函数解决了

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

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

感谢大家。

【讨论】:

    【解决方案3】:

    如果您使用.autotitle,那么更改将应用​​于您使用.autotitle 作为class 属性的每个元素...

    您可以使用特定元素的id 属性仅将更改应用于该元素

    例如:

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

    【讨论】:

      【解决方案4】:

      很多时候,当基于字母数的文本较长时,人们想减小字体大小(使其更小) (文本可能是通过某些 CMS 或翻译文本输入的)

      http://jsfiddle.net/jfbrLjt2/

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        • 2016-09-24
        • 1970-01-01
        • 1970-01-01
        • 2012-01-01
        • 1970-01-01
        • 2011-05-13
        相关资源
        最近更新 更多