根据窗口宽度修剪字符串,调整大小时出现问题
Trim string depending on window width, issue on resize
我想修剪使用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演示
相关文章:
- 内部分区字体大小获胜'调整浏览器窗口大小时不会随媒体查询而更改
- 调整窗口大小时,可拖动的对象会出现在容器外部
- 调整屏幕大小时更改属性值
- 如何在调整浏览器大小时将图像保持在适当位置
- 加载/调整大小时未切换图像数据标记
- 可以在调整窗口大小时重新调整stellar.js的元素偏移量
- 为移动设备调整页面大小时,引导模式会向下移动页面
- 可滚动元素,如何在调整大小时更改顶部偏移量
- 调整UIWebview的大小'更改其字体大小时的边框
- 如何获得一个进度元素,它被设置为在窗口调整大小时调整大小
- 在调整窗口大小时刷新浏览器(仅在展开或放大时)
- 调整父元素大小时,文本会移动
- 调整大小时移动在高图表上呈现的图像
- 根据窗口宽度修剪字符串,调整大小时出现问题
- jquery在调整大小时响应不起作用
- ExtJS 4-在调整窗口大小时,溢出的工具栏会失去控制器
- 如何在窗口调整大小时调整iframe的大小
- Css-是否可以在调整屏幕大小时使元素移动,以使其适合屏幕
- 调整浏览器大小时文本上的CSS省略号
- 画布FPS在调整屏幕大小时发生变化-Javascript