是否可以计算div中此可用空间的px宽度?
https://www.screencast.com/t/fG1C7uTHjJF
HTML:
<div>Hello world! Code is my life</div>
CSS:
div {
width: 150px;
font-size: 30px;
border: 1px solid black;
}
答案 0 :(得分:0)
让我们想象我的div元素是id = myDiv:
function getTextWidth(text, font) {
// re-use canvas object for better performance
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
}
var remainingSize = $(&#39; #mydiv&#39;)。width() - getTextWidth($(&#39; #mydiv&#39;)。text(),30);
答案 1 :(得分:-1)
var length = $('#mydiv').text().split(" ").length-1;