作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个输入元素,我想要做的是当用户键入时,此静态文本将始终出现在用户输入之后。
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/
我是一名优秀的程序员,十分优秀!