看看这个例子:https://jsfiddle.net/qpysmb9t/
只要contentEditable元素中的文本大于div的最大宽度(尝试输入一些长文本),它的左侧部分就会被隐藏,并显示右侧的内容。键入时没关系,但在重点关注时,我想将其反转并从头开始显示文本。
<div tabindex="-1" contenteditable="true" class="name-data">This is test</div>
.name-data{
max-width:180px;
white-space: nowrap;
overflow-x: hidden;
}
通常的答案是将插入符号的位置移动到开始位置,但是这并不能一直移动文本,而且还会使元素不再聚焦。签出:https://jsfiddle.net/qpysmb9t/1/
您建议我做什么?
答案 0 :(得分:2)
一些JavaScript会有所帮助。当div失去焦点时,我们可以使用scrollLeft
返回到开始位置。
//scroll the text back to the beginning when focus is lost
document.querySelector("div.name-data[contenteditable='true']").addEventListener("blur", function(e){
this.scrollLeft = "0px";
}, true);
.name-data{
max-width:180px;
white-space: nowrap;
overflow-x: hidden;
border: 1px solid #949494;
}
<div tabindex="-1" contenteditable="true" class="name-data">This is test</div>
答案 1 :(得分:1)
想法:当用户将焦点移到浏览器上以强制重新绘制内容时,使div display: flex
并切换justify-content
适当
仅CSS解决方案:
.project-name-data {
max-width: 180px;
white-space: nowrap;
overflow-x: hidden;
display: flex;
justify-content: flex-start;
align-items: center;
flex-wrap: wrap;
border: solid 1px gray;
}
.project-name-data:focus{
justify-content: flex-end;
}
<div tabindex="-1" contenteditable="true" #projectName class="project-name-data">This is test</div>
我喜欢仅CSS的解决方案,但它很奇怪,因为div内容的对齐方式不同于两个状态焦点和正常状态。所以我添加了一些javscript来修复它
JavaScript解决方案:
document.getElementsByClassName("project-name-data")[0].addEventListener("focusout", function() {
this.style.justifyContent = "flex-end";
// Wait a tick then change the justifyContent back to force browser re-paint
setTimeout(() => {
this.style.justifyContent = "flex-start";
}, 0)
});
.project-name-data {
max-width: 180px;
white-space: nowrap;
overflow-x: hidden;
display: flex;
justify-content: flex-start;
align-items: center;
flex-wrap: wrap;
border: solid 1px gray;
}
<div tabindex="-1" contenteditable="true" #projectName class="project-name-data">This is test</div>