根据窗口宽度修剪字符串,调整大小时出现问题

Trim string depending on window width, issue on resize

本文关键字:调整 小时 问题 字符串 窗口 修剪      更新时间:2023-09-26

我想修剪使用javascript允许的字符数。它在加载时工作,但在调整大小时,数字会变为0。为什么?它可以在没有插件的情况下完成吗?

注:

text-overflow属性在这里没有帮助,因为我需要更多的行。

不是背景图像的css破解(文本溢出两行省略号)

没有jquery插件。

谢谢!

function trimWords(){//change number of words depending on width in the category blog page
    var theString = $(".trimmed-words").html(); //the string
    var contentWidth = $(document).width(); //get width of browser
    if(contentWidth < 600){
        var maxLength = 80 // maximum number of characters to extract
    }
    else if (contentWidth >= 600 && contentWidth < 1025){
        var maxLength = 400 		
    }
    else if (contentWidth >= 1025 && contentWidth < 1279){
        var maxLength = 40 		
    }
    else if (contentWidth >= 1279){
        var maxLength = 75 		
    }
    //trim the string to the maximum length
    var trimmedString = theString.substr(0, maxLength);
    //re-trim if we are in the middle of a word
    trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")));
    $(".trimmed-words").html(trimmedString);
}
trimWords();
$(window).resize(trimWords)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="trimmed-words">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

您没有将原始值存储到字符串中。查看我的JS Fiddle

var trimmedStringOriginal = $(".trimmed-words").html();
trimWords();
$(window).resize(trimWords)

http://jsfiddle.net/s0svqyv4/

加载时,我将字符串存储在一个变量中,然后每次调整大小时都会引用该变量。

您使用的是修剪后的值,我看不到您存储原始字符串的任何位置。因此,每次触发调整大小例程时,都会减少字符串。您应该将字符串的完整版本保存在某个位置,并根据完整字符串而不是更改后的字符串来评估需要写入内容区域的内容。除此之外,您的代码应该可以正常工作。

 var theString = $(".trimmed-words").html(); //the string

应该在trimWords()函数之外。

它在调整大小期间不起作用,因为theString变为""为空。

JSBIN演示