首页 > 解决方案 > 当文本填充可见输入长度时阻止输入

问题描述

我有一个绝对定位在画布元素上的 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);

当文本填充输入的可见宽度时,如何防止用户输入。在以下示例中应该停止文本,当用户输入另一个键时,应该阻止输入:

在此处输入图像描述“dsads”

我想避免文本光标随着输入更多输入而移动,即默认行为是这样的:

在此处输入图像描述 “dsadssss”


我以前曾考虑使用诸如maxlengthoninput事件之类的属性,但无法想出具有这种预期效果的任何组合

标签: javascriptjqueryhtmlcssinput

解决方案


这是一个示例,希望对您有所帮助,或者您可以参考它来解决您的问题。

$("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,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  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"  />


推荐阅读