检测元素内的文本是否已达到最大宽度

时间:2018-09-24 20:48:45

标签: javascript jquery

我有我的 HTML 代码:

<input type="text" class="testinput">
<span class="output-text"></span>

,我有我的 CSS

.output-text {
     max-width:300px;
}

然后是我的 jQuery

$(".testinput").keyup(function(){
     var text = $(this).val();
     $(".output-text").text(text);
});

我想知道在输入input时,它会检查每个keyup的文本长度,但是我想知道何时到达{{1}的max-width },方法是发送.output-text

3 个答案:

答案 0 :(得分:0)

您可以执行以下操作,使用输入类型的文本并将内容粘贴到不可见的div中。

var inputElem = document.getElementById('input'),
  fakeElem = document.getElementById('fakeElem');

inputElem.oninput = function() {
  fakeElem.innerText = inputElem.value;
  if(fakeElem.clientWidth > 300) {
    alert('Hi');
  }
}
#fakeElem {
  width: auto;
  display: inline-block;
  visibility: hidden;
  position: fixed;
  overflow:auto;
}
<input id='input' type='text'>
<div id='fakeElem'></div>

答案 1 :(得分:0)

尝试使用.css()

$(".testinput").keyup(function(){
 var text = $(this).val();

 if($('.output-text').width() > parseInt($(".output-text").css('max-width'))) { //your max-width
    alert('success');
 }

 $(".output-text").text(text);
});

请注意,$(".output-text").css('max-width')返回值加上测量单位的字符串,因此它将返回字符串'300px' '100vw''100%'。如果您在CSS上具有基于百分比的值,视口值或计算出的值,则以上代码将不起作用。

希望这会有所帮助。

答案 2 :(得分:0)

您可以使用jQuery的.width()来检查跨度的宽度。

var output = $(".output-text");
$(".testinput").keyup(function(){
     var text = $(this).val();
     output.text(text);
     if(output.width()>300){
     //more than max-width 300px
     console.log('Output width has exceeded 300px: '+output.width());
     alert('Success!');
     }
});
.output-text {
     max-width:300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="testinput">
<span class="output-text"></span>

相关问题