javascript - 当某个类存在时,jQuery 将 div 字符限制为 90

标签 javascript jquery html css

我试图将一个元素的字符限制在 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/

相关文章:

javascript - 类型错误:在制作自定义选择框/下拉列表时无法读取未定义的属性 'items'

javascript - 为什么我的功能不会停止?

jquery - 选中相应列中的所有复选框

javascript - 注册表单中被点击的图像

html - 如何在不滚动的情况下使网页完全适合屏幕大小?

javascript - 如何在javascript中添加延迟

javascript - 以某种方式使用 CSS 引用哈希值

javascript - Angular 点击事件共享给其他点击

javascript - 通过单击 jQuery 中的 <li> 提交表单

html - CSS - 不同的类,但链接颜色不变