j查询限制文本函数

jQuery limit text function

本文关键字:文本 函数 查询      更新时间:2023-09-26

我正在使用列CSS,我想做的是创建一个jQuery函数,当段落的文本达到一定数量的文本时,该函数调用一个名为"内容列"的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 语句来声明段落的长度,我只是不完全确定如何或从哪里开始。

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

但是你可以通过以下方式计算字母:

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

你可以这样做 - 你需要确保你的文本在父元素中,如下所示:

<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;
}

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

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

或者,如果您不真正关心特定的并迭代,则可以获得所有这些。

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

斯菲德尔