我在一个网站上工作,该网站有一个文本框可以输入价格折扣,当有人在文本框中输入数字时,我希望百分比自动添加到输入中。我相信这真的很容易,但我是Javascript的新手,我还没能在SO.上找到任何东西
<div>
<label for="discount">Enter discount</label>
<input type="text" name="discount" id="discount" oninput="addPercent()">
</div>
谢谢!
我建议您在输入字段旁边使用%作为文本。
<div>
<label for="discount">Enter discount</label>
<input type="text" name="discount" id="discount" oninput="addPercent()">
<span class="percent">%</span>
</div>
如果您仍然需要将其添加到输入字段,我建议在输入模糊上添加事件侦听器。
您可能还需要一些额外的验证来检查输入的整数。此外,一旦焦点从输入中移除,模糊事件就会触发。使用keyup/keydown,如果用户在输入字段中键入值的速度过快,则可能会出现竞争情况。
document.getElementById('discount').addEventListener('blur', function() {
this.value = this.value.replace('%','')+'%'; //remove existing % and add again
});
<div>
<label for="discount">Enter discount</label>
<input type="text" name="discount" id="discount">
</div>
只添加一个"%"到CCD_ 1中的文本末尾可能是足够的,但是过滤CCD_"更好:
将输入事件绑定到<input>
document.querySelector('input').oninput = function(e) { //...
获取<input>
.replace()
的当前值,无论该值不是数字或点。然后加上"%"到值的末尾。
this.value = this.value.replace(/[^d.]/g, '') + '%';
接下来,获取值的结束位置
let end = this.value.length;
然后创建一个从结束位置向后一个字符长度的选择范围。
this.setSelectionRange(end, end-1);
最后,设置.focus()
,使光标始终位于"%"之前">
this.focus()
你确定你想要一个"%"实际价值?如果你打算处理这个值,那么为了计算百分比而删除它将是一个额外的步骤。
document.querySelector('input').oninput = function(e) {
this.value = this.value.replace(/[^d.]/g, '') + '%';
let end = this.value.length;
this.setSelectionRange(end, end-1);
this.focus();
}
<input>