【问题标题】:Align text input contents to right responsively响应式将文本输入内容右对齐
【发布时间】:2019-10-17 01:54:36
【问题描述】:

我正在创建一个自定义输入选择器。它使用文本输入来显示选择并使用按钮供用户进行选择。类似于下面的sn-p:

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>

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

只有当文本对于文本框来说太长时,我才能将输入框的内容向右对齐?

【问题讨论】:

  • 你能用float:right代替text-align吗:对`
  • @Akshay,我正在尝试对齐输入框的内容而不是输入框本身

标签: javascript html css media-queries


【解决方案1】:

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

只需注册一个函数来检查您的输入实际包含的文本长度,并将带有text-align:right; 的css 类切换到窗口的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
 }

【讨论】:

    【解决方案2】:

    据我所知,不使用纯 css,使用 javascript,您可以挂钩多个事件,并根据输入元素宽度检查输入字符串长度,如果字符串长于其长度,则将后者的内容向右对齐。 (窗口调整大小,输入变化)

    【讨论】:

      【解决方案3】:

      你可以使用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>

      【讨论】:

      • 不正确,只要输入的值实际上比输入的宽度长,操作只想将其右对齐,为什么不使用 text-align: right 而不是更改其读数方向..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      • 2017-04-30
      • 2014-06-07
      • 2015-12-15
      相关资源
      最近更新 更多