日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JS获取鼠标光标位置并在光标位置添加内容

發布時間:2024/1/18 javascript 75 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JS获取鼠标光标位置并在光标位置添加内容 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目標需求

  • 獲取鼠標光標位置,然后點擊按鈕或其他事件,在鼠標光標的位置插入需要的文字等

準備工具

  • contenteditable:contenteditable屬性指定元素內容是否可編輯。
  • window.getSelection(): 獲取鼠標光標位置
  • window.getSelection().getRangeAt(params):getRangeAt把鼠標光標在的位置分成前后兩端,getRangeAt得到的是一個數組,params通常是數組的下表,我們這里寫0
  • createRange():返回新創建的Range對象,可以用來表示文檔的一個區域或與該文檔相關的 DocumentFragment 對象。

HTML

react寫法

<div id="contentTable" className={styles['infoBox']} placeholder='請輸入內容' contentEditable suppressContentEditableWarning onblur={this.blurDiv} />

注意??

  • 當不寫suppressContentEditableWarning這個屬性的時候,有可能會拋出警告:Warning: A component is contentEditable and contains children managed by React.

CSS

如果我們想給我div加一個placeholder的話,如下:

.infoBox {width: 100%;height: 115px;padding: 16px;line-height: 1;outline: none;&:empty::before {content: attr(placeholder);color: #808080;}}

JS

// 光標從id為content的div標簽失焦的觸發blurDivblurDiv = () => {const positionObj = window.getSelection().getRangeAt(0)// setState是react自帶的api,這里把positionObj存起來,其他方法用的到this.setState({ positionObj })}// 插入動作modalOk = () => {const { item } = this.state// item為要插入的相關信息this.insertFun(item)}// 插入某個位置insertFun = item => {const { positionObj } = this.state// contentWrap是拿到上面👆div的dom,react如果拿不到真實dom的話,可以用ref或者useRef獲取真實的domconst contentWrap = document.getElementById('contentTable')const range = document.createRange()if (contentWrap.childNodes.length == 0) {contentWrap.appendChild(this.handleCreateContent(item))} else {// 這里判斷positionObj是否為undefined,是因為第一添加的時候是undefined,第一次添加的時候直接insertNode到id為contentTable這個父節點if (positionObj == undefined) {range.setStart(contentWrap.childNodes[0], 0)range.setEnd(contentWrap.childNodes[0], 0)range.insertNode(this.handleCreateContent(item))return}range.setStart(positionObj.startContainer, positionObj.startOffset)range.setEnd(positionObj.startContainer, positionObj.startOffset)range.insertNode(this.handleCreateContent(item))}}// 處理要插入什么內容handleCreateContent = item => {const { dropMenuType, name, pagePath } = itemconst width = this.getTextWidth(`{${name}}`)const input = document.createElement('input')input.setAttribute('class', 'input')input.setAttribute('value', `{${name}}`)input.setAttribute('disabled', false)input.style.width = `${width + 5}px`input.style.border = 'none'return input}// 獲取文字的寬度,因為input的寬度不能用width:fit-content自適應,并且這里用input標簽的原因是因為想把要插入的內容當作一個整體(光標選不中input里面的內容,只能選input的前后)getTextWidth = str => {let dom = document.createElement('span')dom.setAttribute('id', 'textWidth')dom.style.display = 'inline-block'dom.textContent = strdocument.body.appendChild(dom)const w = document.getElementById('textWidth').clientWidthdocument.body.removeChild(document.getElementById('textWidth'))return w}// 最后,我們插入完,獲取id為contentTable里面的內容getContent = () => {const contentWrap = document.getElementById("contentTable");// contentWrap.childNodes(數組的格式)里面就是我們要的數據,我們處理一下就可以了console.log(contentWrap.childNodes)}

總結

以上是生活随笔為你收集整理的JS获取鼠标光标位置并在光标位置添加内容的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。