响应式地将文本输入内容对齐

Align text input contents to right responsively

我正在创建自定义输入选择器。它使用文本输入来显示选择,并使用按钮供用户进行选择。它类似于以下代码段:

inputDisplay = document.getElementById("inputDisp");
choosePath = () => {
 const newpath = prompt("Enter new long path", "a/long/long/long/long/long/verylong/long/long/long/long/long/long/verylong/long/path/to/folder/");
 inputDisplay.value = newpath;
}

document.getElementById("btnSel").addEventListener("click", choosePath
);
input {
  width:100%;
}
@media screen and (max-width: 640px){
  input{
  text-align:right;
  }
}
<input id="inputDisp" readonly value="a/path/to/a/folder/">
<button id="btnSel">Select path</button>

我想要的是,当用户调整屏幕大小时,如果 space 剩余的空间不足以显示整个路径,它会将文本右对齐。我以为我可以使用媒体查询,但如果你输入一个短路径并且它正确对齐,它看起来不太好。

有什么办法可以让输入框的内容在文本框太长的时候右对齐吗?

据我所知,对于纯 css,对于 javascript,您可以挂钩多个事件并根据输入元素宽度检查输入字符串长度,并将后者的内容对齐到右侧如果字符串长于它的长度。 (window 调整大小,输入更改)

你可以使用direction rtl/ltr来解决这个问题:

inputDisplay = document.getElementById("inputDisp");
choosePath = () => {
 const newpath = prompt("Enter new long path", "a/long/long/long/long/long/verylong/long/long/long/long/long/long/verylong/long/path/to/folder/");
 inputDisplay.value = newpath;
}

document.getElementById("btnSel").addEventListener("click", choosePath
);
input {
  direction: ltr;
}
@media screen and (max-width: 640px){
  input{
    direction: rtl;
  }
}
<input id="inputDisp" readonly value="a/path/to/a/folder/">
<button id="btnSel">Select path</button>

没有 css 方法可以实现您的目标,因为这需要访问功能层而不是表示层。您仍然可以通过使用一些 javascript 事件处理程序设法做到这一点。

只需注册一个函数来检查您输入的实际包含的文本长度,并将 css class 与 text-align:right; 切换到 [=28= 的 resize 事件上] 和输入元素的 keydown 事件。

有关事件的更多信息,请参阅 w3school 上的 DOM 事件文档: https://www.w3schools.com/jsref/dom_obj_event.asp

您可以像这样检查输入中的当前文本长度:

 var value = document.getElementById('inputDisp').value;
 if (value.length > 20 && window.innerWidth <= 640) {
   // Toggle CSS class with text alignment right
 } else {
   // Toggle CSS class with text alignment left
 }