use*_*788 1 html javascript css contenteditable
我有一个 contenteditable 元素,它大概应该以相对较小的宽度开始,然后当您将内容放入其中时,它会扩展直到达到最大宽度,剪裁内容。
我希望它像文本框一样“回滚”到开头。我试过将插入符号位置设置为开始,它确实有效,但不会“回滚”。我也尝试将内容设置为空(“”),然后在 1 毫秒后在 setTimeout 的帮助下恢复到原来的状态,尽管这是一个非常肮脏的解决方案:(
我不能为此使用文本框,因为我只希望双击后可以编辑内容。有人可以帮忙吗?
HTML:
<section contenteditable='true'>Edit me!</section>
Run Code Online (Sandbox Code Playgroud)
CSS:
section {
background-color:#ccc;
display:inline;
white-space:nowrap;
max-width:100px;
position:absolute;
overflow:hidden;
padding:10px;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 .scrollLeft 设置溢出的滚动位置。我已经使用 'onblur' 属性让你的部分在该部分不再是焦点时触发,它传递this给我们的函数使用而不是稍后获取元素:
<section contenteditable='true' onblur="resetOverflowPosition(this)">This should be long enough to mean that you can scroll forward and the script will scroll backwards</section>
Run Code Online (Sandbox Code Playgroud)
这里我们设置scrollLeft为0重置当前栏目的滚动,你可以多次使用这个功能:
function resetOverflowPosition(element){
element.scrollLeft = 0;
}
Run Code Online (Sandbox Code Playgroud)
这是一个 JSFiddle:https ://jsfiddle.net/np72zxo0/2/ 。如果您需要更多帮助,请随时发表评论。