2013-02-14 99 views
4

我有多篇文章,但他们都需要适合在同一个空间。字符被限制为140.我要做的是根据我的段落中的字符调整字体大小。所以如果段落的字符少了,我想字体大小变大&反之亦然。基于字数设置字体大小jquery

我的下面的代码似乎并没有工作,并想知道如果有人能够帮助我吗?

发生了什么事的那一刻,它似乎是走过去的东西,因为所有段落的字体大小8em :(

非常感谢所有帮助&在此先感谢!

这里验证码:

$(function(){ 
    var $quote = $(".question p"); 
    var $numWords = $quote.text().split("").length;  
    if (($numWords >= 1) && ($numWords < 20)) { 
     $quote.css("font-size", "2.2em"); 
    } 
    else if (($numWords >= 20) && ($numWords < 60)) { 
     $quote.css("font-size", "1.8em"); 
    } 
    else if (($numWords >= 60) && ($numWords < 100)) { 
     $quote.css("font-size", "1.2em"); 
    } 
    else if (($numWords >= 100) && ($numWords < 140)) { 
     $quote.css("font-size", "0.9em"); 
    } 
    else { 
     $quote.css("font-size", "0.8em"); 
    }   
}); 
+0

有一个插件为此已:) :) https://gist.github.com/mekwall/1263939 – 2013-02-14 22:45:55

+0

这不会解决你的问题,但你应该重新命名你的$ numWords变量,因为你分裂时的数字字符“”,而不是文字。 – ChrisC 2013-02-14 22:48:59

+0

嘿它似乎在这个小提琴工作正常> http://jsfiddle.net/u3fyu/ – dev 2013-02-14 22:50:56

回答

4

你的问题是你不能单独处理每个段落:看http://jsfiddle.net/wkEMK/1/

$(function(){ 
    $(".question p").each(function() { 
     var numChars = $(this).text().length;  
     if ((numChars >= 1) && (numChars < 20)) { 
      $(this).css("font-size", "2.2em"); 
     } 
     else if ((numChars >= 20) && (numChars < 60)) { 
      $(this).css("font-size", "1.8em"); 
     } 
     else if ((numChars >= 60) && (numChars < 100)) { 
      $(this).css("font-size", "1.2em"); 
     } 
     else if ((numChars >= 100) && (numChars < 140)) { 
      $(this).css("font-size", "0.9em"); 
     } 
     else { 
      $(this).css("font-size", "0.8em"); 
     }   
    }); 
}); 

您的原始代码获得了匹配'.question p'的所有段落的字符数。例如如果你有两个段落,一个是十个字符,另一个是二十个字符,你的JS会运行一次,共有三十个字符,而不是依次处理每个段落。

3

做这样使用.css功能..这样,它会根据每一p组件内字符的数目的每个p个元素字体大小改变

$(function(){   
    $(".question p").css('font-size',function(){ 
     var $numWords = $(this).text().length; // get length of text for current p element 
     if (($numWords >= 1) && ($numWords < 20)) { 
      return "2.2em"; 
     } 
     else if (($numWords >= 20) && ($numWords < 60)) { 
      return "1.8em"; 
     } 
     else if (($numWords >= 60) && ($numWords < 100)) { 
      return "1.2em"; 
     } 
     else if (($numWords >= 100) && ($numWords < 140)) { 
      return "0.9em"; 
     } 
     else { 
      return "0.8em"; 
     }   
    });  
}); 

FIDDLE

+0

谢谢!而已!!! – dennisterrey 2013-02-14 23:04:08