【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)
相关推荐
ziyue75751 分钟前
vue修改element-ui的默认的class
前端·vue.js·ui
树叶会结冰23 分钟前
HTML语义化:当网页会说话
前端·html
冰万森28 分钟前
解决 React 项目初始化(npx create-react-app)速度慢的 7 个实用方案
前端·react.js·前端框架
牧羊人_myr41 分钟前
Ajax 技术详解
前端
浩男孩1 小时前
🍀封装个 Button 组件,使用 vitest 来测试一下
前端
蓝银草同学1 小时前
阿里 Iconfont 项目丢失?手把手教你将已引用的 SVG 图标下载到本地
前端·icon
布列瑟农的星空1 小时前
重学React —— React事件机制 vs 浏览器事件机制
前端
一小池勺2 小时前
CommonJS
前端·面试
孙牛牛2 小时前
实战分享:一招解决嵌套依赖版本失控问题,以 undici 为例
前端