gpt4 book ai didi

javascript - 如何将静态文本添加到输入值

转载 作者:行者123 更新时间:2023-12-02 16:40:27 25 4
gpt4 key购买 nike

我有一个输入元素,我想要做的是当用户键入时,此静态文本将始终出现在用户输入之后。

h "staticTextHere"
hello "staticTextHere"
hello world "staticTextHere"

我尝试了一些技术,但这里有很多问题。有什么想法如何实现这一目标吗?

这是我的代码;

<input type="text" id="staticTextId" name="staticTextName" ..... />

还有js;

.on('keydown', function (event) {
var textLength = document.getElementById($id).value.length;
document.getElementById($id).value = document.getElementById($id).value.substr(0,textLength - staticText.length) + staticText;
});

最佳答案

纯 JS 版本:Demo online

jQuery:Demo online

document.getElementById("staticTextId").addEventListener('keyup', function(){
var str = this.value;
var suffix = " static text";

if(str.search(suffix) === -1){
str += suffix;
}

var actualLength = str.length - suffix.length;

// set the value
this.value = str.substr(0,actualLength) + suffix;

// set cursor position
this.setSelectionRange(actualLength,actualLength);
});

关于javascript - 如何将静态文本添加到输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27548894/

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