我正在创建一个自定义的输入选择器。它使用文本输入来显示选择,并使用按钮让用户进行选择。它类似于下面的代码片段:
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>
我想要的是,当用户调整屏幕大小时,如果没有足够的空间显示整个路径,它会将文本向右对齐。我认为我可以使用媒体查询,但如果你输入一个短路径,它正确地对齐,它看起来就不是那么好了。
有没有一种方法,当文本对文本框来说太长时,我才能将输入框的内容靠右对齐?
发布于 2019-10-16 15:56:30
没有实现目标的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
}发布于 2019-10-16 15:38:52
据我所知,在纯css中,使用javascript可以连接到几个事件,并检查输入字符串的长度和输入元素的宽度,如果字符串比它的长度长,则将输入元素的内容右对齐。(调整窗口大小,更改输入)
发布于 2019-10-16 15:41:31
您可以使用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>
https://stackoverflow.com/questions/58407882
复制相似问题