Skip to content
On this page

useTextSelection

获取用户选中的字符串以及其位置信息

获取到的 数据是相对于视图的左上角计算的(除 height,width外)

位置信息回参参考

兼容性参考

Demo

可选择区域: asdasasdsadsadsadasd eeeeeeeeeeeeeeee

已选择的值:
位置信息:rect: { "left": null, "right": null, "top": null, "bottom": null, "height": null, "width": null }
left: NaN

Usage

html
<template>
  <div>
    <p ref="p">可选择区域: asdasasdsadsadsadasd eeeeeeeeeeeeeeee</p>
    <div>已选择的值:{{ text }}</div>
    <div>位置信息:rect: {{ rect }}</div>
    <div>left: {{ rect.left }}</div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useTextSelection } from '@morehook/core'

const p = ref()
const { text, rect } = useTextSelection(p)
</script>

Type Declarations

typescript
type Target = HTMLElement | Ref<HTMLElement> | (() => HTMLElement) | Document
/**
 * 获取用户选中的字符串
 * @param target 指定在哪个元素下的选中
 * @returns text: 选中的内容字符串 rect: 参照 https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect
 * @tips 获取到的 数据是相对于视图的左上角计算的(除 height,width外)
 */
export declare function useTextSelection(target?: Target): ToRefs<{
  text: string
  rect: {
    left: number
    right: number
    top: number
    bottom: number
    height: number
    width: number
  }
}>

Source

SourceDemoDocs