我试图将一个元素的字符限制在 90 个字以内。但是当点击显示更多按钮时,它应该取消限制。
我尝试使用一个类来执行此操作并将限制附加到该类,然后在单击显示更多按钮时删除该类。
我的尝试:
<header>
<h1>Heading Goes Here</h1>
<p class="jumbo-p non-exp">
The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.
</p>
<a href="#" class="more1">more</a>
</header>
CSS:
.jumbo-p{display: inline-block; height: 20px; overflow: hidden;}
.more1 {position: relative; left: 2px; top: -21px;}
.jumbo-p.expanded+.more1 {display: none}
.jumbo-p.expanded {height: auto;}
使一切正常的 jQuery:
$(".non-exp").text(function(index, currentText) {
return currentText.substr(0, 90) + '...';
});
$(document).on('click', '.more1', function(event) {
event.preventDefault();
$('.jumbo-p').toggleClass('expanded');
$('.jumbo-p').removeClass('non-exp');
});
这对 div 施加了限制,但是当类被删除时该限制并没有被删除。请帮忙。
最佳答案
问题是您用“...”替换了文本。您需要通过将原始文本存储在某处并在单击“更多”按钮时再次显示它来撤消此更改。
还有一点,我看到你说过
text-overflow will limit it based on div width. i want to limit it based on character length
可以根据字符数设置div的宽度,像这样
width: 90ch;
但是,可能存在一些浏览器兼容性问题。查看更多信息 Specify width in *characters*
关于javascript - 当某个类存在时,jQuery 将 div 字符限制为 90,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32303592/