文字可编辑 contenteditable && 默认选中

1. 知识点

  • contenteditable 属性可作用于html的节点上,取值为boolean类型,取值true时节点内容可编辑。
  • getSelection / selection 页面元素选中

2. 使用

  ···
  <div id='fonts'>麦壳社区~</div>
  ···
  const _fonts = document.getElementById('fonts')
  _fonts.addEventListener("dblclick",function(){
     // 设置元素可编辑
     _fonts.setAttribute('contenteditable',true)
     if(window.getSelection){
        const range = document.createRange()
        range.selectNodeContents($(this)[0])
        window.getSelection().removeAllRanges() // 清楚其他的选中状态
        window.getSelection().addRange(range) // 添加元素选中住那个改
      }
  },false)

3. 小记

  // 获取当前选中内容
  if(window.getSelection){
     const selectRange = window.getSelection()
     const rangeTarget = selectRange.getRangeAt(0)
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容