[UPDATE]: I later on figure out a stupid way to handle it(not always works, but most time):
Style:
#txt_ruler {
position: fixed;
top: -100px;
left:-100px;
visibility: hidden;
}
HTML:
<div id="txt_ruler"></div>
JS:
String.prototype.visualLength = function(style) {
var ruler = $("#txt_ruler")[0];
if(style["font-weight"]){
d3.select("#txt_ruler").style("font-weight", style["font-weight"]);
}else {
d3.select("#txt_ruler").style("font-weight", null);
}
d3.select("#txt_ruler").style("font-size", style["font-size"]);
ruler.innerHTML = this;
return ruler.offsetWidth;
}
String.prototype.visualText = function(style, width) {
var l = this.visualLength(style);
if(l<=width){
return this.toString();
}else {
var percent = width/l;
var breakIndex = Math.floor(this.length*percent);
var tmpStr = this.substring(0, breakIndex+1)+ "…";
while(breakIndex>=0 && tmpStr.visualLength(style)>width){
breakIndex--;
tmpStr = this.substring(0, breakIndex+1)+ "...";
}
return tmpStr;
}
}
All:
What I want to do is get the characters left if there is a container overflow.
The way I am thinking about(but still not sure how to do that) currently is to use:
#ofc {
font-size:20px;
display: inline-block;
width:200px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
<div id="ofc">A very1 very2 very3 very4 very5 very6 very7 very8 Long TEXT</div>
What shown on the page is:
A very1 very2 very3 ...
But my current question is:
How can I use jQuery or D3.js or JS to get this crop text with 3 dots, but not the whole?
OR
According to what my purpose, is there a mathematical way to apply specific font-size to it to actually calculate what the text left in a DIV with specific width?