1.0.9 • Published 6 months ago

tdy-clipboard v1.0.9

Weekly downloads
-
License
ISC
Repository
-
Last release
6 months ago

使用文档

在线demo运行

项目根目录下运行命令:npm i tdy-clipboard -g,tdy-clipboard startDemo

复制目标元素中的文本

mainShow

  • html代码片段

    <!-- TargetElement
    <span id="foo">谭达源</span>
    <input id="foo" type="tel" value="110" />
    <p id="foo">tdy</p>
    <input id="foo" type="text" value="tandayuan" />
    -->
    <textarea id="foo">tdydemo</textarea>
    <!-- TriggerElement-->
    <button class="btn" data-clipboard-target="#foo">Copy to clipboard</button>
  • ts代码片段

    new ClipboardStudy(".btn")
  • data-clipboard-target: string | HTMLElement可以用CSS选择器语法或者元素节点对象声明被复制的目标元素

复制文本内容

copyText

  • html代码片段

    <!-- TriggerElement-->
    <button class="btn" data-clipboard-text="my name is tdy">Copy to clipboard</button>
  • ts代码片段

    new ClipboardStudy(".btn")
  • data-clipboard-text: string设置后,点击按钮就会复制到剪切板。

剪切目标元素中的文本

cut

  • html代码片段

    <textarea id="foo">tdydemo</textarea>
    <!-- TriggerElement-->
    <button class="btn" data-clipboard-action="cut" data-clipboard-target="#foo">Copy to clipboard</button>
  • ts代码片段

    new ClipboardStudy(".btn")
  • data-clipboard-action: copy | cut,设置cut就是剪切文本;

自定义的复制/剪切事件监听

image-20231124132330619

  • html代码片段同复制目标元素中的文本章节

  • ts代码片段

    const cs = new ClipboardStudy(".btn");
    cs.on("success", (e) => {
      console.log("复制/剪切事件成功监听,回调参数:", e);
      // 进阶用法:通过回调参数中的方法取消复制选中的区域。
      e.cancelSelectedText()
    })
    cs.on("error", (e) => {
      console.log(e, "error");
    })

其他相关功能

自定义action、text、target行为

  • 同时定义texttarget

image-20231124161230766

  • 仅定义target

image-20231124161300083

  • html代码片段

    <input id="foo1" type="text" value="foo1" />
    <textarea id="foo2">foo2</textarea>
    <!-- TriggerElement-->
    <button class="btn">Copy to foo1 or foo2</button>
  • ts代码片段

    let i = 0
    const cs = new ClipboardStudy(".btn", {
      actionFn(triggerElement) {
        const action = i % 2 === 0 ? "copy" : "cut"
        return action
      },
      textFn(triggerElement) {
        const text = i % 2 === 0 ? "my name is foo1" : "my name is foo2"
        return text
      },
      targetFn(triggerElement) {
        const fooStr = i % 2 === 0 ? "#foo1" : "#foo2"
        return document.querySelector(fooStr) as HTMLElement
      },
      container: document.body
    })
    cs.on("success", (e) => {
      console.log("复制/剪切事件成功监听,回调参数:", e)
      i++
    })
    cs.on("error", (e) => {
      console.log(e, "error")
    })
  • triggerElement是触发行为的元素;

  • 同时定义时,textFn的优先级比targetFn的高;
  • container的用途是target元素位于模态框内,那么container必须设置成模态框DOM对象,功能才可以正常运作;

销毁copy/cut能力

const cs = new ClipboardStudy(".btn");
cs.abortListenEvent()
1.0.9

6 months ago

1.0.8

6 months ago

1.0.7

6 months ago

1.0.6

6 months ago

1.0.5

6 months ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago