我有一个文本输入,我想将其保持在 300 像素的固定宽度。允许文本输入的值超出此范围。当文本确实超出输入范围时,我希望用省略号截断文本,但是当聚焦时,输入应该是水平滚动的。
此行为均由 text-overflow: ellipsis;
提供。问题在于,当未聚焦时,输入仍然可以水平滚动,但由于文本被截断,它只会滚动到空白区域。我怎样才能阻止这种情况发生?
测试以下代码我在 Chrome (108.0) 中遇到了问题,但在 Firefox 或 Safari 中没有。这只是 Chrome 的一个无法避免的特性吗?
<form>
<input
type="text"
style="width: 300px; text-overflow: ellipsis"
value="asdfasdflkajsdlfjalsdfkaslkdfjalskdjflkasjdflkjaldsfkjalsdfjasdfasfasdf"
/>
</form>
这是向右滚动时的样子:Image of unwanted behaviour.
我尝试将 overflow: hidden;
和 white-space: nowrap;
添加到输入中,以及周围表单上的这些属性,上面的 div表单,甚至是围绕表单输入的 div。所有这些都会导致上述规范之外的相同行为或其他行为。
有这个相关问题,但没有令人满意的答案,我已经能够将其缩小为 Chrome 问题... Input element scrollable with text-overflow ellipsis enabled
最佳答案
我认为这是一个已知的 Chrome 问题。您可以使用一点 JavaScript 来解决这个问题,如果这对您有用?
您可能希望只针对 Chrome。
//Locate all elements with class inputContainer
document.querySelectorAll('.inputContainer').forEach(container => {
//Bind a click event to each of those elements (parent)
container.addEventListener("click", function() {
//Turn on pointer-events (defaulted to off in CSS)
//and focus to prevent need to double click for focus
container.querySelector('input').style.pointerEvents = "auto";
container.querySelector('input').focus();
});
});
//Bind a blur event to all input fields to turn pointer-events back to "none"
document.querySelectorAll('input').forEach(input => {
input.addEventListener("blur", function() {
this.style.pointerEvents = "none";
});
});
<form>
<!-- Added container -->
<div class="inputContainer">
<input type="text" style="pointer-events:none;width: 300px; text-overflow: ellipsis" value="asdfasdflkajsdlfjalsdfkaslkdfjalskdjflkasjdflkjaldsfkjalsdfjasdfasfasdf" />
</div>
</form>
关于html - 文本输入在 Chrome 中保持水平滚动, "text-overflow: ellipsis",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74845827/