我正在尝试在被截断的div中获取可见的文本。 例如: 我有一条很长的消息,在某个时候被截断了: “测试消息测试消息...”
我正在寻找一种只检索可见文本而不是整个消息的方法。
$.fn.doOverflow = function(){
return this[0].scrollWidth > this.innerWidth()
}
$.fn.renderedText = function(){
var o = s = this.text();
console.log(s);
console.log(s.length);
while (s.length && this.doOverflow()){
s = s.slice(0,-1);
// console.log(s);
this.text(s+"…");
// console.log(this.text());
}
return s;
}
console.log($('#mySpan').renderedText())
#mySpan{
display:block;
white-space:nowrap;
overflow:hidden;
text-overflow:ellipsis;
width:150px
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<span id=mySpan >This is the contents of the span tag. It should truncate with an ellipsis if it is longer than 50px.</span>
<br>
Open the console
</body>
</html>
还有其他方法可以实现吗?
答案 0 :(得分:0)
如果您可以将文本设置为属性,那么我们可以在不使用javascript的情况下显示工具提示。
*{
box-sizing: border-box;
}
body{
font-family:arial;
}
#mySpan{
display:block;
padding:10px;
border:1px solid #eee;
margin:10vh 5vh;
border-radius:3px;
position:relative;
}
#mySpan:before{
content:attr(data-content);
display:block;
white-space:nowrap;
text-overflow:ellipsis;
overflow:hidden;
}
#mySpan:hover::after{
position:absolute;
background:#333;
white-space: normal;
color:#fff;
top:calc(100% + 10px );
left:0;
padding:10px;
font-size:.85em;
content:attr(data-content);
display:block;
border-radius:5px;
box-shadow:2px 2px 6px 3px rgba(0,0,0,.15);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<span id="mySpan" data-content="This is the contents of the span tag. It should truncate with an ellipsis if it is longer than 50px. Use text-overflow:ellipsis instead of javascript."> </span>
</body>
</html>