jQuery限制文本功能

时间:2015-03-06 16:11:34

标签: javascript jquery html css

我正在处理CSS列,我想要做的是创建一个jQuery函数,该函数调用一个名为" Content Columns"的CSS类。当段落的文本达到一定数量的文本时。否则它会保持width: 100%

这是我使用

的CSS
-moz-column-count: 2;
-moz-column-gap: 10px;
-moz-column-rule: none;
-webkit-column-count:2;
-webkit-column-gap: 10px;
-webkit-column-rule: none;
column-count: 2;
column-gap: 10px;
column-rule: none;
margin-top:10px;

我知道我需要制作一个声明段落长度的if语句,我不完全确定如何或从哪里开始。

3 个答案:

答案 0 :(得分:0)

您可以这样做 - 您需要确保您的文字位于以下父元素中:

<div class="text-group">
    <p>Haero nibh a turpis. Facilisi valetudo ut suscipit pecus olim nulla ad ut et. Autem vindico enim.</p>
    <p>Sino consequat dolore tincidunt tation vulputate valetudo antehabeo.</p>
</div>

然后在你的剧本中:

var threshold = '200' // cutoff number of characters to be 2-col
$('.text-group').each(function(i) {
     if ($(this).text().length > threshold) {
         $(this).addClass('content-columns');
     }
});

CSS :(没有前缀)

.content-columns {
    column-count: 2;
    column-gap: 10px;
    column-rule: none;
    margin-top:10px;
}

答案 1 :(得分:0)

这取决于您想要检查的操作,还取决于您使用它的元素。在文本框上你应该在其他元素上使用.val()你应该使用html()或text(),这取决于你是否需要内部html长度或纯文本。您还可以添加另一个事件侦听器,例如change,document keyup,etf。

但你可以通过以下方式来计算:

&#13;
&#13;
var maxLength = 5;
$('.box').on('keyup',function(){
  if($('.box').val().length >= maxLength){
   alert("You have reached "+maxLength+" letter");
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="box"></textarea>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

如果您的段落有ID,您可以使用选择器抓取它们并在.text()上调用.length。

$('#1').text().length

如果你真的不关心特定的那些并且迭代,你可以得到所有这些。

paragraphs = $('p').get()
$.each(paragraphs, function (index) {
 console.log($(this).text().length);
});

jsfiddle