美文网首页
插入表情(文字)到指定光标位置

插入表情(文字)到指定光标位置

作者: vinoooooo | 来源:发表于2019-08-07 20:49 被阅读0次

    函数代码:

        faceClick(idx: number, word: string) {
            let { temList } = this.state;
            temList[idx] = this.insertText(
                this.refs[`script-input-${idx}`],
                `[${word}]`
            );
            this.setState({
                temList: [...temList]
            });
        }
    
        insertText(obj: any, str: string) {
            if (document.selection) {
                var sel = document.selection.createRange();
                sel.text = str;
            } else if (
                typeof obj.selectionStart === "number" &&
                typeof obj.selectionEnd === "number"
            ) {
                var startPos = obj.selectionStart,
                    endPos = obj.selectionEnd,
                    cursorPos = startPos,
                    tmpStr = obj.value;
                obj.value =
                    tmpStr.substring(0, startPos) +
                    str +
                    tmpStr.substring(endPos, tmpStr.length);
                cursorPos += str.length;
                obj.selectionStart = obj.selectionEnd = cursorPos;
            } else {
                obj.value += str;
            }
            return obj.value;
        }
    

    JSX

        <input
            type="text"
            className="tem-input"
            value={item}
            placeholder="请输入内容"
            onChange={this.TemChange.bind(
                this,
                index
            )}
            ref={`script-input-${index}`}
        />
        <Face
            onClick={this.faceClick.bind(
                this,
                index
            )}
        />
    

    相关文章

      网友评论

          本文标题:插入表情(文字)到指定光标位置

          本文链接:https://www.haomeiwen.com/subject/zlzadctx.html