从狭窄的输入中仅获取文本值的实际可见部分(获取输入“滚动”)

时间:2018-10-21 22:24:58

标签: javascript html

我的<input type="text">较窄,输入字段中的文字“不适合”。

如何仅获得用户可见的文本范围?

示例1:

An example of long input text [An exam] 全文为“这是长输入文本的示例”,但是输入只有7个字符宽,并且光标位于开头,因此只有“考试”适合输入,这是我想要的文本要得到。

示例2:

An example of long input text [long in] 相同的文本,但是用户将光标向前移动,所以我想获得“ long in”

2 个答案:

答案 0 :(得分:1)

假设字体始终为monospace,要知道一个字符的宽度,我们可以使用以下内容。

let charWidth = document.querySelector('.monospaceCharWidthCheck').getBoundingClientRect().width;
console.log(charWidth)
span {
  padding: 0;
  font-family: monospace;
  border: 0;
  position: absolute;
  left: -9999px;
}
<span class="monospaceCharWidthCheck">a</span>

如果输入的宽度是动态的,要知道可以容纳多少个字母,我们只需将其宽度除以字符宽度,然后用Math.round()除去小数点即可。

let charWidth = document.querySelector('.monospaceCharWidthCheck').getBoundingClientRect().width;
let input = document.querySelector('input');
let inputlettersCapacity = Math.round(input.clientWidth / charWidth);
console.log('How many letters this input can fit visibly : ' + inputlettersCapacity)
document.querySelector('input[type=button]').onclick = (e) => {
  let visibleText;
  if (input.value.length > inputlettersCapacity)
    visibleText = input.value.substring(0, inputlettersCapacity);
  else
    visibleText = input.value;
  console.log(visibleText)
}
input[type=text] {
  font-family: monospace;
  padding: 0;
  outline: none;
  /* 16px to accommodate for the blinking cursor */
  font-size: 16px;
}

span {
  padding: 0;
  font-family: monospace;
  border: 0;
  position: absolute;
  left: -9999px;
  /* Which means we should add it here */
  font-size: 16px;
}
<span class="monospaceCharWidthCheck">a</span>
<input type="text">
<input type="button" value="get visible text">

部分可见的字符,忽略它们或对其计数,我会留给您。

要获得可见值,我使用了一个按钮单击,单击按钮会使输入失去焦点,这会将文本滚动到开头,这对于使用substring十分方便。

答案 1 :(得分:0)

您可以根据输入字段的特定宽度适合的假定字符对它进行硬编码。
在这种情况下,它是An exam = 7(包括空白)。

因此,假设输入的宽度是动态的而不是静态的,则您必须知道在特定宽度内可以容纳多少个字符。

(在这种情况下)执行此操作的一种方法是获取输入字段的前7个字符,如下所示:

var inputText = document.getElementById('myInputId').innerText;
var visibleCharacters = inputText.substring(0, 8);

编辑:

根据您的“示例2”,如果您需要知道光标在哪里,以便从那里获取子字符串,如下所示:

var inputElem = document.getElementById('myInputId');
var inputText = inputElem.innerText;
var cursorIndex inputElem.selectionStart;
var visibleCharacters = inputText.substring(cursorIndex, cursorIndex + 7);

// You are getting the text from cursor point to +7 of that position ( in this case )

当然,这既不是做到这一点的方法,也不是最准确的方法。 这只是我想出的一种技巧。

相关问题