替换...阅读更多(自定义elipses)

时间:2018-05-29 06:55:10

标签: javascript jquery html css

我有一个固定高度和宽度的div,但div的内容是动态的。

我希望仅当elipses处于活动状态时,将 ... 替换为 ...了解更多

任何用于实现此目的的JavaScript代码?

CODE



document.getElementById("read-more").onclick = function(){
	this.style.whiteSpace = "normal";
}

div#read-more{
    width: 90%;
    border: 1px solid #000;
    padding: 8px;
    margin: 48px auto 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

<p>Resize your browser window to see what happens to the text in the box below. When the text is too long, an ellipse is added to the end.</p>
<div id="read-more">Lorem ipsum dolor. Sit in your comfy office chair and OOH and AHH at the cool ellipsis!</div>
&#13;
&#13;
&#13;

JSFiddle Here

2 个答案:

答案 0 :(得分:1)

现在只有firefox似乎有这样的效果,如果你玩

text-overflow: '...readmore';

其他浏览器不响应它。

另一种解决方案是

&#13;
&#13;
var p = document.querySelector(".js-overflow");

if (p.scrollWidth > p.offsetWidth) p.classList.add("has-overflow");

while (p.scrollWidth > p.offsetWidth) {
  p.innerHTML = p.innerHTML.slice(0, -1);
}
&#13;
p {
  width: 200px;
  border: 1px solid;
  padding: 2px 5px;
  /* BOTH of the following are required for text-overflow */
  white-space: nowrap;
  overflow: hidden;
}
.has-overflow:after {
  content: "...readmore"
}
&#13;
<p class="js-overflow">
  Testing overflow yaya look at me !
</p>
&#13;
&#13;
&#13;

了解更多here

答案 1 :(得分:0)

由于Jaromanda X已经评论过使用text-overflow: '... read more';

document.getElementById("read-more").onclick = function() {
  this.style.whiteSpace = "normal";
}
div#read-more {
  width: 90%;
  border: 1px solid #000;
  padding: 8px;
  margin: 48px auto 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: '…read more';
}
<p>Resize your browser window to see what happens to the text in the box below. When the text is too long, an ellipse is added to the end.</p>
<div id="read-more">Lorem ipsum dolor. Sit in your comfy office chair and OOH and AHH at the cool ellipsis!</div>