可编辑div获取光标位置并插入内容

287 阅读1分钟

可编辑div获取光标位置并插入内容

1.let range=window.getSelection().getRangeAt(0) //获取光标位置 2.range.insertNode(span) //在光标起始位置插入node节点 3.range.anchorNode //锚点 (选择的起始节点)

关于selection和range详细点在这 zh.javascript.info/selection-r…

let position = ''
let content = "<img src='https://img-blog.csdnimg.cn/20201014180756927.png?x-oss-process=image/resize,m_fixed,h_64,w_64'>"
function blurEdit() {
    position = window.getSelection().getRangeAt(0)
    console.log("光标位置", window.getSelection(), window.getSelection().anchorNode,position)
}
function clickInsert() {
    const div = document.getElementById('inputContent')
    if (position === '') {
        // 如果div没有光标,则在div内容末尾插入
        div.focus()
        const range = window.getSelection()
        range.selectAllChildren(div)
        range.collapseToEnd()
        position = window.getSelection().getRangeAt(0)
    }
    // 创建一个元素
    const span = document.createElement('span')
    // 插入的按钮不可编辑,设置contenteditable为false
    span.innerHTML = content
    position.insertNode(span)
    
}