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

时间:2015-03-03 16:24:34

标签: javascript jquery css

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

注意:

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

不是css攻击背景图片(Text overflow ellipsis on two lines

没有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)
&#13;
<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>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

应该在trimWords()函数之外。

在调整大小期间它无效,因为theString变为""为空。

<强> JSBIN DEMO

答案 2 :(得分:1)

您没有将原始值存储到字符串中。看看我的JS小提琴

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

http://jsfiddle.net/s0svqyv4/

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

相关问题