javascript - 根据窗口宽度 trim 字符串,调整大小问题

标签 javascript jquery css

我想减少使用 javascript 允许的字符数。它在加载时工作,但在调整大小时数字变为 0。这是为什么?不加插件可以吗?

注意事项:

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

不是 css hack 背景图片 ( 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)
<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/

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

关于javascript - 根据窗口宽度 trim 字符串,调整大小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28836779/

相关文章:

javascript - 尝试使用 CSS 和 Jquery 确定设备类型未按预期工作

html - 选择器 :root in css

javascript - 性能 使用 child.parentNode 与 getElementById 访问父级

javascript - 在 AngularJS 的 HTML img src 中使用字符串连接

jquery - 我如何指示此菜单下的表格已完成

javascript - 验证动态输入字段 Jquery

javascript - 如何同时控制两个滚动条

javascript - 更改D3 geoCircle的大小和 Angular

javascript - 防止事件冒泡在 jquery 中不起作用

css - 如何在angularjs中有一个图像占位符