如何使文字溢出到我的文字输入的左边?

问题描述 投票:0回答:1

我有一个输入字段(宽度可变),其中的文本长度超过了它的显示范围。默认情况下,它显示字符串最左边的部分(即字符串的第一部分),并隐藏多余的部分(最右边的部分,即字符串的末端)。

<input type="text" value="abcdefghijklmnopqrstuvwxyz" style="width: 25%; font-size: 25px; margin: 50px;">

input by default cutting off the end of the string

当人们在输入栏中点击时,可以移动窗口,查看字符串的任何部分。当光标在字符串的末尾时,只显示末尾部分--字符串的第一部分被切断,并被隐藏。

text when focused with cursor at the end

我希望输入字段总是这样的,我倾向于切断字符串的前面,而不是末端(只是因为对于这个特定的输入,字符串的末端比开头更有用)。

使用 text-align: right 不幸的是,它并没有实现这一点--它只是在全文可以容纳的情况下,才会使文本右对齐。

text which can all fit, and is then right aligned

我不希望使用JS来剪切字符串的长度,因为这将阻止用户编辑它。


说白了,我希望这种情况能一直发生,而不是只在通过关注 使用JavaScript将光标放置在文本输入元素的文本末尾。

html css forms
1个回答
1
投票

要实现您所需要的功能,请使用 内容可编辑. 有了它,你可以使用 justify-contentflexbox.

div[type=text] {
  /* Scroll to the end */
  justify-content: flex-end;
  display: inline-flex;
  
  /* Basic display formatting */
  border: solid 1px black;
  height: 20px;
  width: 100px;
  font-family: sans-serif;
  white-space: nowrap;
  overflow: hidden;
  align-items: center;
}
<div type="text" contenteditable="true">abcdefghijklmnopqrstuvwxyz</div>

如果你不喜欢正确的对齐方式,我们可以删除flexbox,并使用javascript来对齐项目。

[...document.querySelectorAll('div[type=text]')].forEach(el => {
  el.scrollLeft = el.scrollWidth;
})
div[type=text] {
  /* Basic display formatting */
  border: solid 1px black;
  height: 20px;
  width: 100px;
  font-family: sans-serif;
  white-space: nowrap;
  overflow: hidden;
  align-items: center;
}
<div type="text" contenteditable="true">abcdefghijklmnopqrstuvwxyz</div>

1
投票

<input type="text" value="abcdefghijklmnopqrstuvwxyz" style="width: 25%; font-size: 25px; margin: 50px;" dir="rtl" onfocus="this.dir='auto';this.scrollLeft = this.scrollWidth;" onfocusout="this.scrollLeft = this.scrollWidth;">

0
投票

这里的解决方案是,你必须添加一个类名来应用css。

<input type="text" class="myclass" value="abcdefghijklmnopqrstuvwxyz" style="width: 
25%; font-size: 25px; margin: 50px;">

该CSS

.myclass{
direction: rtl;
text-align: left;

}

0
投票

谢谢 "滚动 "到长文本输入的最右边。

用滚动宽度。

<input style="width: 100px" value="abcdefghijklmnopqrstuvwxyz">
<input style="width: 100px" value="abcdefghijklmnopqrstuvwxyz">
<input style="width: 100px" value="abcdefghijklmnopqrstuvwxyz">
$('input').each(function(){ $(this).scrollLeft($(this)[0].scrollWidth) })

就像tim说的,dir属性对'<' '>' '' '\'等字符不是一个好的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.