【HTML】通过焦点,获取部分上下文内容

【HTML】通过焦点,获取部分上下文内容

  • 需求

用户从页面中选择部分文字描述,获取这段选中文字,并获取该文字、上两段、下两段内容,作为上下文输入

  • 效果说明

选中绿色框内文字,将黄色框内文字作为上下文传递

  • 代码实现utils.js
js 复制代码
/**
 * 通过焦点元素获取所属标签
 */
export const getElementByRange = range => {
  let element = range.commonAncestorContainer
  while (element.nodeType !== 1) {
    element = element.parentNode
  }
  return element
}

/**
 * 通过标签获取内容
 */
export const getTextContentByElement = element => {
  return element ? element.textContent : null
}

/**
 * 通过焦点获取上下文
 * @param {Range} range 焦点
 * @returns 上下文内容
 */
export const getContextByRange = range => {
  const dom3 = getElementByRange(range)
  // 向上取两个元素
  const dom2 = dom3.previousElementSibling
  const text2 = getTextContentByElement(dom2)
  let text1 = ''
  if (dom2) {
    const dom1 = dom2.previousElementSibling
    text1 = getTextContentByElement(dom1)
  }
  // 向下取两个元素
  const dom4 = dom3.nextElementSibling
  const text4 = getTextContentByElement(dom4)
  let text5 = ''
  if (dom4) {
    const dom5 = dom4.nextElementSibling
    text5 = getTextContentByElement(dom5)
  }
  let text3 = getTextContentByElement(dom3)
  // 向前拼两段
  if (text2) text3 = text2 + '\n' + text3
  if (text1) text3 = text1 + '\n' + text3
  // 向后拼两端
  if (text4) text3 = text3 + '\n' + text4
  if (text5) text3 = text3 + '\n' + text5
  return text3
}
  • 外部调用

方法从上面的utils引入

js 复制代码
import {
  getContextByRange // 通过焦点获取上下文
} from './utils'

const selection = document.getSelection()
const oRange = selection?.getRangeAt(0)
// 上下文
const context = getContextByRange(oRange)
相关推荐
龙-少几秒前
css3 中的伪类和伪元素
前端·css3
全职计算机毕业设计几秒前
基于Web的特产美食销售系统的设计与实现
前端·microsoft·美食
yivifu1 分钟前
CSS3实现提示工具的渐入渐出效果及CSS3动画简介
前端·css·css3
533_2 分钟前
[报错] SyntaxError: invalid property id(就是不支持ES6)
前端·ecmascript·es6
**之火9 分钟前
ES6 对象的扩展(十五)
前端·javascript·es6
没耳朵的Rabbit25 分钟前
Web开发-LinuxGit基础2-本地-git仓库操作
前端·git
没耳朵的Rabbit27 分钟前
Web开发-LinuxGit基础6-本地-.gitignore
前端·数据库
自足29 分钟前
如何在 Vue 和 JavaScript 中截取视频任意帧图片
javascript·vue·web前端
乐吾乐科技37 分钟前
【乐吾乐2D可视化组态编辑器】事件
前端·nginx·编辑器·流程图·uml·数据可视化·大屏端
一个十几年的老程序员39 分钟前
好玩的调度技术-场景编辑器
javascript·c#·net