在 html 输入字段的特定部分下划线

问题描述 投票:0回答:1

我正在开发一个 Vue 项目,其中使用 JS 包,我可以用它来检查单词拼写是否正确。我有一个函数可以将文本分割成单独的单词,然后使用包检查它。然后包返回 true 或 false。

现在我想在用户输入的特定部分下划线以指示拼写错误。 我该怎么做?

<script setup lang="ts">
import { ref, watch } from 'vue';
import Typo from "typo-js";


const inputField = ref('');
const wordsArray = ref<string[]>([]);
//let dictionary = new Typo("en_US", false, false, {dictionaryPath: "../typo/dictionaries/"});
const dictionary = new Typo("en_US");

function extractWords(text: string): string[] {
  const cleanText = text.replace(/[.,!?;:]/g, '').toLowerCase();
  const words = cleanText.split(/\s+/);
  return words.filter(word => word.length > 0);
}


watch(inputField, (newValue) => {
  wordsArray.value = extractWords(newValue);
  console.log(wordsArray.value[wordsArray.value.length-1]);
  const is_spelled_correctly = dictionary.check(wordsArray.value[wordsArray.value.length-1]);
  console.log(is_spelled_correctly);
  const array_of_suggestions = dictionary.suggest(wordsArray.value[wordsArray.value.length - 1]);
  console.log(array_of_suggestions);

});
</script>

<template>
  <input type="text" v-model="inputField" />
  <div>
  </div>
</template>

<style scoped>

</style>

我尝试将错误的单词作为 html 项目返回,但这似乎也不起作用。

javascript html vue.js frontend spelling
1个回答
0
投票

要在 Vue.js 输入字段中为拼写错误的单词添加下划线,您可以通过将拼写错误的单词包装在 a 中并应用 CSS 样式进行突出显示来动态修改内容。

以下是如何使用 Typo.js 进行拼写检查来实现此目的的示例:

脚本

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import Typo from "typo-js";

const inputField = ref('');
const dictionary = new Typo("en_US");

// Helper function to extract words from the input
function extractWords(text: string): string[] {
  const cleanText = text.replace(/[.,!?;:]/g, '').toLowerCase();
  return cleanText.split(/\s+/).filter(word => word.length > 0);
}

// Function to highlight misspelled words
function highlightText(text: string): string {
  const words = extractWords(text);
  return words.map(word => {
    const isSpelledCorrectly = dictionary.check(word);
    if (!isSpelledCorrectly) {
      return `<span class="misspelled">${word}</span>`;
    }
    return word;
  }).join(' ');
}

// Computed property to generate highlighted text
const highlightedText = computed(() => {
  return highlightText(inputField.value);
});

</script>

模板

<template>
  <div>
    <input type="text" v-model="inputField" />
  </div>
  <!-- Render the highlighted text -->
  <div v-html="highlightedText"></div>
</template>

CSS

<style scoped>
.misspelled {
  text-decoration: underline;
  color: red;
}
</style>

说明:

  1. extractWords 函数:清理文本,将其拆分为单词,然后 返回单词数组。
  2. highlightText 函数:使用 Typo.js 检查每个单词。拼写错误 单词被包裹在带有“拼写错误”的类中。
  3. highlightedText(计算):这是一个响应式属性, 生成最终的 HTML 字符串,其中突出显示拼写错误的单词 每当用户的输入发生变化时。
  4. v-html:用于安全地渲染 HTML 字符串(突出显示 字)在模板中。

这会在输入内容中用红色强调拼写错误的单词。

© www.soinside.com 2019 - 2024. All rights reserved.