gpt4 book ai didi

javascript - 我如何使用事件 @select 从 Vue.js 中的段落中选择一些文本?

转载 作者:行者123 更新时间:2023-12-01 21:59:26 25 4
gpt4 key购买 nike

我在 SSR 中使用带有 Nuxt 的 Vue.js,我希望当我突出显示一些文本时获取该文本并对其执行操作。

我找到了一种方法来处理 <input> 中的一些文本但我希望在这里能够从段落中而不是从输入中@select 一些文本。

这是我使用 <input> 的方式:

<template>
<div>
<input @select="testFunction2()" value="TEXTE TO SELECT">
</div>
</template>

mounted() {
window.addEventListener('select',this.testFunction2,innerHTML)
},
methods:{
testFunction2(event) {
console.log(event.target.value.substring(event.target.selectionStart, event.target.selectionEnd));
},

我试图用“innerHTML”替换“listener”代码中的“value”,但它似乎不起作用,

谢谢!

编辑:我使用了 Terry 提出的方法,它在段落中运行良好。但是当我想在 Vue 组件的 v 循环中突出显示从数据库返回的对象上的一些文本时,我收到此错误:'Uncaught TypeError: Failed to execute 'contains' on 'Node': parameter 1 is not类型为“节点”。 在 HTMLDocument。”

这是我在 vue 组件上返回的对象,该对象实际上是一个 html 文本,我用 v-html 将其转换为纯文本:

<li   v-for=" itemJournal in journalContent"> 
<b-row>
<b-col col lg="10" id="myNoteList" class="htmlNonUser grey-text text-
darken-2 myNoteList" style=""><p v-html="itemJournal.content"
ref="target"> </p>
</b-col>
</b-row>


mounted:function(){
document.addEventListener('mouseup', event => {
if (event.target === this.$refs.target ||
event.target.contains(this.$refs.target))
this.testFunction1();
});
},

testFunction1(event){

console.log(window.getSelection().toString());
},

最佳答案

select 事件仅由类似输入的元素支持。如果您想在常规元素中获取选定的文本,只需监听 mouseup 事件。 mouseup 事件应调用一个函数,您只需调用 window.getSelection().toString() 即可检索所选文本。

在下面的示例中,我们将 mouseup 监听器绑定(bind)到 document,并在事件处理程序中执行额外的过滤,以便只有感兴趣的元素(在本例中, this.$refs.target) 将触发获取选择的回调:

new Vue({
el: '#app',
mounted() {
document.addEventListener('mouseup', event => {
if (event.target === this.$refs.target || event.target.contains(this.$refs.target))
this.testFunction();
});
},
methods: {
testFunction() {
console.log(window.getSelection().toString());
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input @select="testFunction" value="Text to select" />
<p ref="target">Lorem ipsum dolor sit amet</p>
</div>

更新:根据您的回答,您可能想要更新 event.target 所比较的对象(例如,如果您不希望触发任何选择testFunction()), 或者完全离开 if 条件:

document.addEventListener('mouseup', event => {
this.testFunction1();
});

关于javascript - 我如何使用事件 @select 从 Vue.js 中的段落中选择一些文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54215429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com