簡體   English   中英

JavaScript根據div的高寬將長字符串拆分成數組

[英]JavaScript split long string into array based on div height and width

我有一個很長的字符串,我試圖顯示一個div

我的目標:

我試圖根據我可以在 div 中顯示的字數(根據寬度和高度決定)將該大字符串拆分為數組。

代碼:

    data1 = data1.split(" "); // data1 is the original string, here I am obtaining words
    const len = data1.length;

    const wordcount = 105; // 105 is hard-coded that I am tying to automate 105 means div will have only 105 words and below I am storing 105 words in page array at each index 
    let page = []
    for (let i = 0; i < (len / wordcount); i++) {
        page.push(data1.slice(wordcount * i, wordcount * (i + 1)).join(" "))
    }

我加入的時候,我從顯示的文本下面的代碼page[0]page[1] page[0]已經正確填寫股利而不是page[1]問題是,我無法弄清楚如何決定詞對頁面的每個索引進行計數,使其完全填滿 div 框。

我正在嘗試創建一個自定義文本閱讀器,這就是我這樣做的原因。

 let data = "dfgdfgdf gdfg dfsdfsdfsdfs dfsdfsdf dfgdfgdfgdfgd fgdfgdfgdfg d fg df g dfg df gdf g dfgdfg dfgdfgdfdfgdfgdf gdfg dfsdfsdfsdfs dfsdfsdf dfgdfgdfgdfgd fgdfgdfgdfg d fg df g dfg df gdf g dfgdfg dfgdfgdfdfgdfgdf gdfg dfsdfsdfsdfs dfsdfsdf dfgdfgdfgdfgd fgdfgdfgdfg d fg df g dfg df gdf g dfgdfg dfgdfgdf" let width = $('#box').width() let height = $('#box').height() // now based on above width and height I am trying to create a function that will tell how many words I can use to split text it can be same words on each index or variable - this what I am unable to think let wordcount = 8; // let say I get 8 from some algo let data1 = data.split(" "); const len = data1.length; let page = [] for (let i = 0; i < (len / wordcount); i++) { page.push(data1.slice(wordcount * i, wordcount * (i + 1)).join(" ")) } $("#data").text(page[0]+"") $("#data1").text(page[1]+"")
 .abc { border: 1px solid red; width: 130px; height: 105px; white-space: wrap; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="abc" id="box"> <p id="data"></p> </div> <div class="abc"> <p id="data1"></p> </div>

為此,您需要比較使用Element#getBoundingClientRect獲得的DOMRectbottom屬性,同時考慮padding DOMRect只能為元素獲取,不能單獨獲取文本,因此我們首先需要將span的所有單詞都包裹起來。

請注意,每次運行此代碼時,它都會覆蓋#page元素的內容。 如果您想在這樣做的情況下計算分頁,則需要克隆該元素並渲染一個具有相同寬度和高度的不可見 ( opacity: 0 ) 版本。 為了讓事情相對簡單,我沒有在這里這樣做。

 // utils const mod = (n, modulus) => ((n % modulus) + modulus) % modulus const last = arr => arr.slice(-1)[0] // elements const page = document.querySelector('#page') const paginator = document.querySelector('#paginator') const pageCount = document.querySelector('#page-count') // best to set these in the JS to make sure the values line up when calculating distance from bottom const [paddingY, paddingX] = [20, 15] page.style.padding = [paddingY, paddingX].map(n => `${n}px`).join(' ') // main logic const createWordSpans = text => text .split(/(\\s+)/) .map((str, idx) => { if (!str) return null if (idx % 2) { return document.createTextNode(str) } else { const span = document.createElement('span') span.textContent = str return span } }) .filter(Boolean) // note that this rewrites the content of the element const paginateByBoundingElement = parent => text => { parent.textContent = '' const { bottom } = parent.getBoundingClientRect() const pages = [[]] for (const node of createWordSpans(text)) { parent.appendChild(node) if (node.nodeType === Node.ELEMENT_NODE) { const rect = node.getBoundingClientRect() if (rect.bottom + paddingY > bottom) { pages.push([node.textContent]) parent.textContent = '' parent.appendChild(node) } else { last(pages).push(node.textContent) } } else { last(pages).push(node.data) } } return pages.map(page => page.join('')) } // getContent() just returns a string - see below const pages = paginateByBoundingElement(page)(getContent()) page.textContent = pages[0] pageCount.textContent = pages.length paginator.addEventListener('input', e => { if (!e.currentTarget.value.length) return const newPageIdx = mod((parseInt(e.currentTarget.value) || 0) - 1, pages.length) const humanFriendly = String(newPageIdx + 1) page.textContent = pages[newPageIdx] page.dataset.page = humanFriendly e.currentTarget.value = humanFriendly }) function getContent() { return `In the northern ocean there is a fish, called the Kun, many thousand li in size. This Kun changes into a bird, called the Peng, whose back is many thousand li in breadth. With a mighty effort it rises, and its wings obscure the sky like clouds.\\n\\nAt the equinox, this bird prepares to start for the southern ocean, the Celestial Lake. And in the Record of Marvels we read that when the Peng flies southwards, the water is smitten for a space of three thousand li around, while the bird itself mounts upon a typhoon to a height of ninety thousand li, for a flight of six months' duration.\\n\\nJust so are the motes in a sunbeam blown aloft. For whether the blue of the sky is its real colour, or only the result of distance without end, the effect to the bird looking down would be just the same as to the motes.` }
 * { box-sizing: border-box; } #page { width: 12em; height: 15em; border: 5px solid #ddd; white-space: pre-wrap; position: relative; } #page::after { content: attr(data-page); color: #ccc; position: absolute; right: 5px; bottom: 5px; } #paginator { font-size: 1em; width: 3em; }
 <div id="page" data-page="1"></div> <br> <label>Page <input id="paginator" type="number" step="1" value="1"> of <span id="page-count">1</span></label>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM