jquery 添加换行符和截断 +添加“...”在 x 个字符之后
我正在尝试找出一种方法来完成两件事:
1. 4 个字符或第一个单词后换行。
2.截断+添加“...”(仅当字符数超过20个字符时)
示例:2008 WALKER STATION THE BRIDGE 1.5L
希望显示:
2008年
WALKER STATION ...
我需要 #1 每次都发生,但如果文本超过 20 个字符,则只需要 #2。
我已经用以下代码分解了该行:
$(window).load(function(){
$(".wine-name").each(function() {
var html = $(this).html().split(" ");
html = html[0] + "<br>" + html.slice(1).join(" ");
$(this).html(html);
});
HTML:
<div class="wine-name">2008 WALKER STATION THE BRIDGE 1.5L</div>
I'm trying to figure out a way to accomplish 2 things:
1. A line break after 4 characters or first word.
2. Truncate + add "..." (only if the amount of characters exceed 20 characters)
Example: 2008 WALKER STATION THE BRIDGE 1.5L
Would like it to display:
2008
WALKER STATION ...
I need #1 to happen every time, but only #2 if the text is more 20 characters.
I've got the line breaking down with the following code:
$(window).load(function(){
$(".wine-name").each(function() {
var html = $(this).html().split(" ");
html = html[0] + "<br>" + html.slice(1).join(" ");
$(this).html(html);
});
HTML:
<div class="wine-name">2008 WALKER STATION THE BRIDGE 1.5L</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在这里:
现场演示: http://jsfiddle.net/XpmpQ/1/
Here you go:
Live demo: http://jsfiddle.net/XpmpQ/1/
一种方法是使用:
JS Fiddle demo。
One way of doing this is to use:
JS Fiddle demo.
好吧,你可以使用
text-overflow
属性以 CSS 方式设置它,该属性得到了很好的支持(但由于某些奇怪的原因不在 FF 中),具体取决于你的需要,CSS 方式(没有任何脚本) )会完成这项工作,甚至更好。如果您不知道我在说什么,请通过搜索text-overflow ellipsis
来查看 Google。如果您已经知道这一点,很抱歉打扰,我只是指出了一个我认为会有所帮助的替代方案。
Well, you may set up it the CSS way using
text-overflow
property which is pretty weill supported (but not in FF for some strange reason), depending on your needs, the CSS way (without any script) would do the job, or even better. Have a look at Google by searchingtext-overflow ellipsis
if you don't know what I'm talking about.Sorry to bother if you already know this, I just pointed out an alternative that I thought would help.
我想你正在寻找这样的东西:
jsFiddle demo
I think you are looking for something like this:
jsFiddle demo