我有一個帶有動態文本值的 div 標簽,我想找到如何根據字體大小和 div 寬度計算字串展開的行數
例如:
div {
width: 15px
fontSize: 12px
overflow: hidden
display: block
overflow-wrap: break-word
}
字串是:“abcdefghijk”
UI 中的結果將是:
第一行 - “abc” 第二行 - “defg” 第三行 - “hijk”
所以預期的計算值應該是 3(3 行)。
有沒有可能計算出來?
http://jsfiddle.net/b6upgdqz/15/
uj5u.com熱心網友回復:
我想您還必須明確行高,然后將包含 div 的總高度除以您設定的行高...
const input = document.getElementById("text");
const container = document.getElementById("container");
const rows = document.getElementById("rows");
input.addEventListener("input", function handleInputChange(event) {
updateRowsCount(event.currentTarget.value);
});
function updateRowsCount(text) {
writeText(text);
computeRows(container);
}
function writeText(text) {
container.innerHTML = text;
}
function computeRows(container) {
const style = window.getComputedStyle(container);
const containerHeight = parseFloat(style.height);
const lineHeight = parseFloat(style.lineHeight);
const rowsCount = Math.ceil(containerHeight / lineHeight);
rows.innerHTML = rowsCount;
}
updateRowsCount(input.value);
#sample {
display: flex;
align-items: flex-start;
}
#sample > * {
margin-right: 2rem;
}
#container {
width: 15px;
font-size: 12px;
line-height: 1.2;
overflow: hidden;
display: block;
overflow-wrap: break-word;
background: pink;
}
<div id="sample">
<input id="text" value="abcdefghijkl" />
<div id="container"></div>
<div id="rows"></div>
</div>
uj5u.com熱心網友回復:
作業演示: https : //dojo.telerik.com/EzEjucOF/5
var calculateLineCount = function (element) {
var lineHeightBefore = element.css("line-height"),
boxSizing = element.css("box-sizing"),
height,
lineCount;
// Force the line height to a known value
element.css("line-height", "1px");
// Take a snapshot of the height
height = parseFloat(element.css("height"));
// Reset the line height
element.css("line-height", lineHeightBefore);
if (boxSizing == "border-box") {
// With "border-box", padding cuts into the content, so we have to subtract
// it out
var paddingTop = parseFloat(element.css("padding-top")),
paddingBottom = parseFloat(element.css("padding-bottom"));
height -= (paddingTop paddingBottom);
}
// The height is the line count
lineCount = height;
return lineCount;
}
$("#lineCount").html("Total number(s) of line : " calculateLineCount($(".divwrap")));
div {
width: 22px;
font-size: 12px;
overflow: hidden;
display: block;
overflow-wrap: break-word;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divwrap">
abcdefghijk
</div>
<h2 id="lineCount"></h2>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/397919.html
標籤:javascript css 节点.js 反应
