Я делаю текстовый редактор, а вот код: -
const editor = document.querySelector('#ta');
const lc = document.querySelector('#line-count');
var lcDiv = document.createElement('p');
var calculateContentHeight = function( ta, scanAmount ) {
var origHeight = ta.style.height,
height = ta.offsetHeight,
scrollHeight = ta.scrollHeight,
overflow = ta.style.overflow;
/// only bother if the ta is bigger than content
if ( height >= scrollHeight ) {
/// check that our browser supports changing dimension
/// calculations mid-way through a function call...
ta.style.height = (height + scanAmount) + 'px';
/// because the scrollbar can cause calculation problems
ta.style.overflow = 'hidden';
/// by checking that scrollHeight has updated
if ( scrollHeight < ta.scrollHeight ) {
/// now try and scan the ta's height downwards
/// until scrollHeight becomes larger than height
while (ta.offsetHeight >= ta.scrollHeight) {
ta.style.height = (height -= scanAmount)+'px';
}
/// be more specific to get the exact height
while (ta.offsetHeight < ta.scrollHeight) {
ta.style.height = (height++)+'px';
}
/// reset the ta back to it's original height
ta.style.height = origHeight;
/// put the overflow back
ta.style.overflow = overflow;
return height;
}
} else {
return scrollHeight;
}
}
var calculateHeight = function() {
var ta = document.getElementById("ta"),
style = (window.getComputedStyle) ?
window.getComputedStyle(ta) : ta.currentStyle,
// This will get the line-height only if it is set in the css,
// otherwise it's "normal"
taLineHeight = parseInt(style.lineHeight, 10),
// Get the scroll height of the textarea
taHeight = calculateContentHeight(ta, taLineHeight),
// calculate the number of lines
numberOfLines = Math.ceil(taHeight / taLineHeight);
for(let i = 1; i < numberOfLines; i++){
lcDiv = document.createElement('p');
lcDiv.id = 'lcDiv';
lcDiv.innerHTML = i;
lc.appendChild(lcDiv);
}
};
calculateHeight();
if (ta.addEventListener) {
ta.addEventListener("mouseup", calculateHeight, false);
ta.addEventListener("keyup", calculateHeight, false);
} else if (ta.attachEvent) { // IE
ta.attachEvent("onmouseup", calculateHeight);
ta.attachEvent("onkeyup", calculateHeight);
}
#ta{
resize: none;
width: 95%;
line-height: 5vh;
height: 90vh;
background-color :#4C5760;
color: #EFD09E;
font-size: 5vh;
float: left;
}
#line-count{
float: left;
}
<div id="line-count"></div>
<textarea id="ta"></textarea>
Я ожидал, что он добавит номера строк при формировании новой строки. Но, похоже, он не выходит за пределы 1, и процесс повторяется, когда я добавляю буквы. Может кто-нибудь решить эту проблему. Я ожидаю, что он будет отображать номера строк обычным способом, как текстовые редакторы, такие как Atom, код Visual Studio и т. Д. Справка и ответы приняты.