javascript - 当文本填充可见输入长度时阻止输入
问题描述
我有一个绝对定位在画布元素上的 html 输入。宽度设置为与背景中画布元素的右边框相接(突出显示)。
根据用户将绿色圆圈放在输入左侧的位置,输入实际上附加到较大的画布元素:
var input = jQuery('<div><input id="edit-annotation-input" ' +
'style="z-index: 100; position: absolute; top:' + (this.textPosition.y - 9) + 'px; left:'+ (this.textPosition.x + 8) +'px; width: ' + (610 - 7 - this.textPosition.x) + 'px; border: none; color: #0bac3a; outline: none; background-color: transparent !important; padding: 0px; font-family: arial; font-size: 12pt; " ' +
'spellcheck="false" type="text" name="mytext[]" value="'+string+'"/></div>');
jQuery("div #pad").append(input);
当文本填充输入的可见宽度时,如何防止用户输入。在以下示例中应该停止文本,当用户输入另一个键时,应该阻止输入:
我想避免文本光标随着输入更多输入而移动,即默认行为是这样的:
我以前曾考虑使用诸如
maxlength
和oninput
事件之类的属性,但无法想出具有这种预期效果的任何组合
解决方案
这是一个示例,希望对您有所帮助,或者您可以参考它来解决您的问题。
$("input[name=testInput]").on('keydown keyup',function(event){
var $that = $(this);
var widthOfInput = getWidthOfInput(document.getElementById("testInput")) ;
var cssWidth = $that.width();
//console.log('widthOfInput'+ widthOfInput);
//console.log('widthInputCss'+ widthInputCss);
// accept key backspace
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 ){
return true;
}
// check limit input
if(cssWidth < widthOfInput){
event.preventDefault();
}
});
function getWidthOfInput(inputEl) {
var tmp = document.createElement("span");
tmp.className = "input-element tmp-element";
tmp.innerHTML = inputEl.value.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
document.body.appendChild(tmp);
var theWidth = tmp.getBoundingClientRect().width;
document.body.removeChild(tmp);
return theWidth;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="testInput" name="testInput" style="width:100px" />
推荐阅读
- shiny - 基于pickerinput选择的闪亮更新表格内容
- javascript - 测试一个 redux 函数
- reactjs - 我是否正确使用了 useEffect 和取消订阅?
- php - 嗨,我正在尝试解析谷歌结果页面以提取所有 URL
- angular - 如何从以下本地 json 文件访问密钥?
- reactjs - 忽略 React App 中服务 index.html 文件中的特定 url
- python - 可点击的字形在散景上生成图
- list - 如何防止 NavigationView 影响子视图
- arrays - System.InvalidCastException:“指定的演员表无效。” 来自 Json API 的 Xamarin Spinner 数组
- java - QueryDsl BooleanBuilder:如何创建一个比较列表内容的谓词?