How to use text-overflow ellipsis in an html input field?

My web page has input fields to which I have applied the following css :

.ellip {
white-space: nowrap;
width: 200px;
overflow: hidden;
-o-text-overflow: ellipsis;
-ms-text-overflow: ellipsis;
text-overflow: ellipsis;
}

But this doesn't seem to have any effect. Am I missing something obvious here or is it not possible to have an ellipsis in an input field using CSS only?

81594 次浏览

字段是有自己规则的元素。输入字段的实现方式是,如果文本比字段长,那么文本就不会被看到。

这样做的原因是,如果您在表单中使用字段,并且可以使用文本溢出省略号,那么它将只传输被截断的内容,这不是想要的效果。

根据我的测试,Chrome、 Safari 和 Firefox 现在都支持它。

不过它们确实有些许不同的效果。

在模糊火狐附加... 右侧的文本,但只有当有任何文本隐藏在右侧的文本框。

而在模糊浏览器中,Chrome 似乎会跳到文本的开头,然后在文本的末尾添加... ... ,而不管你把文本的滚动位置放在哪里。

我知道这是一个老问题,但我也遇到了同样的问题,并且遇到了适合我的 这篇博文来自《前端技巧与魔术》,所以我想我应该分享一下,以防人们仍然感到好奇。博客的要点是,您可以在 IE 中的输入中做省略号,但只有当输入具有 readonly属性时才可以。

显然,在许多场景中,我们不希望输入具有只读属性。在这种情况下,您可以使用 JavaScript 来切换它。这段代码直接取自博客,所以如果您觉得这个答案有帮助,您可以考虑查看博客并给作者留下表示感谢的评论。

// making the input editable
$('.long-value-input').on('click', function() {
$(this).prop('readonly', '');
$(this).focus();
})


// making the input readonly
$('.long-value-input').on('blur', function() {
$(this).prop('readonly', 'readonly');
});
.long-value-input {
width: 200px;
height: 30px;
padding: 0 10px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="long-value-input-container">
<input type="text" class="long-value-input" value="sdghkjsdghhjdfgjhdjghjdfhghjhgkdfgjnfkdgnjkndfgjknk" readonly />
</div>

在输入本身上设置 text-overflow:ellipsis对我来说很有用。当输入失焦时,它会截断并放置省略号。