In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use the Web rich text input box". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use the Web rich text input box".
Input box is rich in text
The traditional input box is used to make, its advantage is very simple, but the disadvantage is that the picture can not be displayed. In order to enable the input box to display images (rich text), we can use the setting of the contenteditable= "true" property to achieve this function.
Simply create an index.html file and write the following:
Open the browser and you will see an input box with a picture by default:
The cursor can move before and after the picture, enter content, and even delete the image with the backspace key-in other words, the image is part of the editable content, which means that the rich text of the input box has been reflected.
The next task is to think about how to paste the picture directly through control + v.
Handle paste events
Anything copied through "copy" or control + c (including screenshots) is stored on the clipboard and can be monitored in the onpaste event in the input box when pasting.
The contents of the clipboard are stored in the DataTransferItemList object, which can be accessed through e.clipboardData.items:
Careful readers will find that if you click the small arrow in front of DataTransferItemList directly in the console, you will find that the length property of the object is 0. What about the contents of the clipboard? In fact, this is a small pit for Chrome debugging. In developer tools, the object that comes out of console.log is a reference that changes as the original data changes. Because the clipboard data has been "pasted" into the input box, the DataTransferItemList you see after expanding the small arrow becomes empty. To do this, we can use console.table to show real-time results.
Once you understand where the clipboard data is stored, you can write code to process them. Because our rich text input box is relatively simple, we only need to deal with two types of data, one is ordinary text type data, including emoji expressions, and the other is picture type data.
Create a new paste.js file:
Const onPaste = (e) = > {/ / if there is no data on the clipboard, return if (! (e.clipboardData & & e.clipboardData.items)) {return} / / encapsulated in Promise to facilitate future use of return new Promise ((resolve, reject) = > {/ / the location of copied content in the clipboard is uncertain So make sure the data is accurate for (let I = 0, len = e.clipboardData.items.length) by traversing all the time. I
< len; i++) { const item = e.clipboardData.items[i] // 文本格式内容处理 if (item.kind === 'string') { item.getAsString((str) =>{resolve (str)}) / / Image format content processing} else if (item.kind = 'file') {const pasteFile = item.getAsFile () / / processing pasteFile / / TODO (pasteFile)} else {reject (new Error (' Not allow to paste this typefaces'))} }})} export default onPaste
Then you can use it directly in the onPaste event:
Document.querySelector ('.editor') .addEventListener ('paste', async (e) = > {const result = await onPaste (e) console.log (result)})
The above code supports text formatting, and then it's time to deal with the picture format. Students who have played will know that all file format content, including pictures, will be stored in File objects, which is the same on the clipboard. So we can write a set of general functions to read the content of the picture in the File object and convert it into a base64 string.
Paste a picture
In order to better display the picture in the input box, the size of the image must be limited, so this image handler can not only read the picture in the File object, but also compress it.
Create a new chooseImg.js file:
/ * Preview function * * @ param {*} dataUrl base64 string * @ param {*} cb callback function * / function toPreviewer (dataUrl Cb) {cb & & cb (dataUrl)} / * * Image Compression function * * @ param {*} img Picture object * @ param {*} fileType Picture Type * @ param {*} maxWidth Picture * * width * @ returns base64 string * / function compress (img, fileType MaxWidth) {let canvas = document.createElement ('canvas') let ctx = canvas.getContext (' 2d') const proportion = img.width / img.height const width = maxWidth const height = maxWidth / proportion canvas.width = width canvas.height = height ctx.fillStyle ='# fff' ctx.fillRect (0,0, canvas.width, canvas.height) ctx.drawImage (img, 0,0, width, height) const base64data = canvas.toDataURL (fileType Canvas = ctx = null return base64data} / * Select picture function * * @ param {*} e input.onchange event object * @ param {*} cb callback function * @ param {number} [maxsize=200 * 1024] Picture * * Volume * / function chooseImg (e, cb) Maxsize = 200 * 1024) {const file = e.target.files [0] if (! file | |! /\ / (?: jpeg | jpg | png) / i.test (file.type)) {return} const reader = new FileReader () reader.onload = function () {const result = this.result let img = new Image () if (result.length {resolve (url)})
Back in the browser, if we copy a picture and perform the paste action in the input box, we can see that the image address starting with data:image/png;base64 is printed on the console.
Insert content into the input box
After the first two steps, we can now read the text and image contents in the clipboard, and then insert them correctly into the cursor position of the input box.
For inserts, we can do this directly through the document.execCommand method. Detailed usage of this method can be found in the MDN documentation, where we only need to use insertText and insertImage.
Document.querySelector ('.editor') .addEventListener ('paste', async (e) = > {const result = await onPaste (e) const imgRegx = / ^ data:image\ / png;base64,/ const command = imgRegx.test (result)? 'insertImage':' insertText' document.execCommand (command, false, result)})
However, in some versions of Chrome browsers, the insertImage method may fail, so you can use another approach, using Selection. It is also used for selecting and inserting emoji later, so you might as well take a look at it first.
When we call window.getSelection () in the code, we get a Selection object. If you select some text on the page, and then execute window.getSelection (). ToString () in the console, you will see that the output is the part of the text you selected.
Corresponding to this part of the area text is a range object that can be accessed using window.getSelection (). GetRangeAt (0). Range contains not only the text of the selected area, but also the start location startOffset and the end location endOffset of the region.
We can also manually create a range through document.createRange (), write to it and display it in the input box.
For inserting a picture, first get the range from window.getSelection (), and then insert the picture into it.
Document.querySelector ('.editor') .addEventListener ('paste', async (e) = > {/ / read the contents of the clipboard const result = await onPaste (e) const imgRegx = / ^ data:image\ / png;base64,/ if it is a picture format (base64), the
The label is inserted in the correct position / / if it is in text format Then insert the text into if (imgRegx.test (result)) {const sel = window.getSelection () if (sel & & sel.rangeCount = 1 & & sel.isCollapsed) {const range = sel.getRangeAt (0) const img = new Image () img.src = result range.insertNode (img) range.collapse (false) sel through the document.execCommand ('insertText') method .removeAllRanges () sel.addRange (range)}} else {document.execCommand ('insertText') False, result)}})
This method can also complete the function of pasting pictures, and the versatility will be better. Next, we will use Selection to complete the insertion of emoji.
Insert emoji
Whether it's pasting text or pictures, our input box is always in focus. When we select emoji emoji from the emoji panel, the input box will be out of focus (blur) and then refocus. Because the document.execCommand method can only be triggered when the input box is in focus, it is not available for handling emoji inserts.
As mentioned in the previous section, Selection allows us to get the start position startOffset and end position endOffset of the selected text in the focus state. If the text is not selected but is only in the focus state, then the values of these two positions are equal (equivalent to selecting the text is empty), that is, the position of the cursor. As long as we can record this position before losing focus, we can insert the emoji into the right place through range.
First, write two tool methods. Create a new cursorPosition.js file:
/ * get the cursor position * @ param {DOMElement} element input box dom node * @ return {Number} cursor position * / export const getCursorPosition = (element) = > {let caretOffset = 0 const doc = element.ownerDocument | | element.document const win = doc.defaultView | | doc.parentWindow const sel = win.getSelection () if (sel.rangeCount > 0) {const range = win.getSelection () .getRangeAt (0) const preCaretRange = range.cloneRange () preCaretRange.selectNodeContents (element) preCaretRange.setEnd (range.endContainer Range.endOffset) caretOffset = preCaretRange.toString (). Length} return caretOffset} / * * set cursor position * @ param {DOMElement} element input box dom node * @ param {Number} cursorPosition cursor position value * / export const setCursorPosition = (element, cursorPosition) = > {const range = document.createRange () range.setStart (element.firstChild, cursorPosition) range.setEnd (element.firstChild) CursorPosition) const sel = window.getSelection () sel.removeAllRanges () sel.addRange (range)}
With these two methods in place, you can put them into the editor node. First record the cursor position in the keyup and click events of the node:
Let cursorPosition = 0 const editor = document.querySelector ('.editor') editor.addEventListener ('click', async (e) = > {cursorPosition = getCursorPosition (editor)}) editor.addEventListener (' keyup', async (e) = > {cursorPosition = getCursorPosition (editor)})
After recording the cursor position, you can insert emoji characters by calling the insertEmoji () method.
InsertEmoji (emoji) {const text = editors [XSS _ clean] / / insert emoji editors [XSS _ clean] = text.slice (0, cursorPosition) + emoji + text.slice (cursorPosition, text.length) / / move one bit after the cursor position to ensure that setCursorPosition (editor, this.cursorPosition + 1) / / updates the locally saved cursor position variables after the newly inserted emoji (note that emoji occupies two bytes So to add 1) cursorPosition = getCursorPosition (editor) + 1 / / emoji occupies two places} Thank you for reading, the above is the content of "how to use Web rich text input box", after the study of this article, I believe you have a deeper understanding of how to use Web rich text input box, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.