【问题标题】:Is there a way to change CSS styles of part of input value?有没有办法改变部分输入值的 CSS 样式?
【发布时间】:2021-08-21 02:29:51
【问题描述】:

所以我正在使用 React.js 创建一个表单,并且特定输入必须与上面写的标签匹配,如下所示:

如果有错别字,则文字变为红色:

现在整个输入值变成红色,这不是我想要的。 有没有办法只针对输入值中的错字字符并更改它们的 css 样式,以便只有这些字符变成红色?

Line.js

import { useState } from "react";

function Line(props){
//State for checking if theres error in the input.
//false >>> no error
//true  >>> has error
let [err, setErr] = useState(false);
let [done, setDone] = useState(false);
//Executes every keystroke
function inputHandler(event){
    const input = event.target.value;

    //console.log(x.slice(-1));
    //console.log(x.length);

    //Compares every char of input to the label
    for (let i = 0; i < input.length; i++) {
        //Error was found in this iteration
        //Set error font color
        if(input[i] !== props.label[i]){
            console.log(input[i] + " did not match " + props.label[i])
            setErr(true);
            return;
        }
        //After last iteration no error was found
        //Set font to normal
        if(i === (input.length-1)){
            setErr(false);
        }
      }
    //if there is no error and I have typed everything from label
    //Set success colour
    if(input.length === props.label.length && !err){
        setDone(true);
    } else {setDone(false)}
}

return <div className="container-fluid form-group d-flex flex-column justify-content-center 
text-center">
    <label className="form-control-plaintext">{props.label}</label>
    <input id='demo' type='text' className={`form-control ${err ? 'text-danger' : null} ${done 
? 'text-success' : null}`} onChange={inputHandler} maxLength={props.label.length}/>
</div>
}

export default Line;

您必须在 index.html 中包含引导链接和脚本才能使这些类正常工作:

https://getbootstrap.com/docs/4.0/getting-started/introduction/

【问题讨论】:

  • 你最好使用 content editable div 来代替 input 。 developer.mozilla.org/en-US/docs/Web/Guide/HTML/…AFAIK 这不可能与输入标签有关
  • 其实这个主意不错
  • 不,您不能设置input 值的一部分。 contentdeitble 是要走的路。
  • 我打算推荐内容可编辑的 div。但老实说,您可以只使用输入的pattern 属性。这不会以不同的颜色出错,但会使输入变为红色并向用户解释必要的模式

标签: javascript html reactjs bootstrap-5


【解决方案1】:

您可以使用可编辑的 div 创建输入组件,然后逻辑处理各种类型的状态。这与富文本编辑器几乎相同。

参考 - https://www.w3schools.com/tags/att_global_contenteditable.asp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 2019-12-19
    • 1970-01-01
    相关资源
    最近更新 更多