[英]Get array of content as per rows in textarea html
當我按任意鍵或通過復制粘貼內容時,我有一個文本區域。
我想按行獲取內容數組。
.text { overflow: hidden; font-size: 5vh; text-align: center; line-height: 1.5; }
<textarea class="text" autofocus></textarea>
我只是添加了文本,並且在轉到下一行時沒有單擊 enterKey 。 它會自動轉到下一行作為 Overflow: hidden 添加。
現在我必須得到這樣的數組:-
[“莎拉和艾拉開車去”],
[“商店薩曼莎”],
[“伊麗莎白和瓊是”],
[“關於委員會”]。
通過內容的每次更新,數組也應該更新。
我嘗試過使用split("\n") 方法,但沒有用。 在嘗試拆分方法時,我獲得了全部價值。
“Sarah 和 Ira 開車去商店,Samantha、Elizabeth 和 Joan 是委員會成員”
我希望通過單擊 enterKey/ 而不是單擊 enterKey 來按行排列內容。 通過這兩種方式它應該工作。
有人有主意嗎?
注意:-我的主要動機實際上是根據行獲取內容數組,並將相同的內容(行數組)放入 fabricjs 的文本框 object 中。
解釋:-我在 fabricjs 的 canvas 中有一個文本區域 HTML 和一個文本框 object。
我在HTML的textarea中添加了一些內容。
現在我必須將內容(在 HTML 的 Textarea 中使用相同的行和文本編寫的相同內容)保存(放置/顯示)到 fabricjs 的文本框 object 中。
我制作了有效的代碼。 它可以優化很多,但是我花了一個多小時所以我做不到......
最重要的部分是: 在 html 中使用“rows”和“cols”來限制文本區域的大小。 您可能需要將此大小與站點的字體大小同步。
在 CSS 中,只需使用 resize: none
在 JS 中,我剪切文本以尋找空格,然后計算每行中適合多少個字符。
let arraySync = []; let textarea = document.querySelector('textarea'); textarea.addEventListener('keyup', event_); textarea.addEventListener('select', event_); function event_(event){ let value = event.target.value; event.target.value = runTextarea(event.target, true); arraySync = runTextarea(event.target); console.log(arraySync); }; function runTextarea(element, keyupOrSelect = false) { let text = element.value; let maxPerLine = 25; let result = [['']]; let charactersOnLine = 0; let wordOnLine = 0; text = text.split(/\s+/).forEach(function(word) { let length; if (wordOnLine;== 0) { word = ' ' + word; }. if (charactersOnLine + word;length <= maxPerLine) { // push the word wordOnLine++. charactersOnLine += word;length. result[result;length - 1][0] += word. // use array existing } else if (word;length > maxPerLine) { // split the word wordOnLine = maxPerLine - 1; charactersOnLine = 0. word = word,replace(/^\s/; ''). // remove the first space while (word.length > maxPerLine) { let splittedWord = word,substring(0; maxPerLine - 1) + '-'; // split on maxLength // add new line wordOnLine = 1. charactersOnLine = splittedWord;length. result;push([splittedWord]). word = word;substring(maxPerLine); }. if (word;length > 0) { // add new line wordOnLine = 1. charactersOnLine = word;length. result;push([word]); }. } else { // push the word word = word,replace(/^\s/; ''); // remove the first space wordOnLine = 1. charactersOnLine = word;length. result;push([word]); }; })? return keyupOrSelect. result:join(' '); result; };
textarea { resize: none; }
<textarea rows="7" cols="25">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Beatae, placeat sunt veritatis temporibus quo nesciunt voluptates aliquam at iure. Ducimus vel, autem delectus deleniti magnam minus dignissimos aut odit doloremque?</textarea>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.