javascript - 限制段落字符的有效方法(垂直文本溢出)

标签 javascript php jquery html css

我正在尝试创建博客页面并考虑限制主要内容长度的最佳方法? (缩略图下的描述)

我正在使用 jQuery 执行此操作,但我正在寻找开发人员执行此操作的通用方法。

或者我可以在后端用 php 限制它。

jQuery(document).ready(function ($) {
    // text limiter
    function textLimit(elements,maxTextLength) {
        for (var i = 0; i < elements.length; i++){
            if (elements[i].innerHTML.length > maxTextLength)
            elements[i].innerHTML = elements[i].innerHTML.slice(0,maxTextLength) + '...';
        }
    }
    
    textLimit($('.content').find('p'),200);
    
});
div.content {
  width: 300px;
  height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
    <a><h4>New Product</h4></a>
    <p>Lorem ipsum is a pseudo-Latin text used in web design, typography, layout, and printing in place of English to emphasise design elements over content. It's also called placeholder (or filler) text. It's a convenient tool for mock-ups. It helps to outline the visual elements of a document or presentation, eg typography, font, or layout. Lorem ipsum is mostly a part of a Latin text by the classical author and philosopher Cicero. Its words and letters have been changed by addition or removal, so to deliberately render its content nonsensical; it's not genuine, correct, or comprehensible Latin anymore. While lorem ipsum's still resembles classical Latin, it actually has no meaning whatsoever. As Cicero's text doesn't contain the letters K, W, or Z, alien to latin, these, and others are often inserted randomly to mimic the typographic appearence of European languages, as are digraphs not to be found in the original.</p>
</div>

谢谢。

最佳答案

有几种方法可以做到这一点。如果您想在 div 中显示部分内容,如上所示,最好使用 PHP:

$string = 'Put your text here...'

// strip tags to avoid breaking any html
$string = strip_tags($string);

// Max length = 200 
if (strlen($string) > 200) {

    // truncate string
    $stringCut = substr($string, 0, 200);

    // OPTIONAL: make sure it ends in a word
    $string = substr($stringCut, 0, strrpos($stringCut, ' ')).'...'; 
}
echo $string;

我希望这能让您更好地了解您的选择!

关于javascript - 限制段落字符的有效方法(垂直文本溢出),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44086278/

相关文章:

PHP:关于 MVC 中的 View 层?

javascript - 使用带间隙的箭头进行水平滚动

javascript - 动态设置 Bootstrap 3 模态标题

javascript - 将 png 图像从 json 链接到 html

javascript - 从特定 IP 地址服务 webpack 开发服务器

javascript - 查找字符串中的两个数字

php - 如何在 Docker 容器中为 PHP 安装 mod_rewrite 模块?

javascript - 如何在HTML和Javascript中使用php?

javascript - 导航时加载 GIF 图像

javascript - D3.horizo​​n 图表不呈现