简体   繁体   English

ContentEditable 元素 — 光标回到可编辑文本的开头

[英]ContentEditable element — cursor back to beginning of editable text

I have a contentEditable header.我有一个contentEditable标题。 It only allows for one line and doesn't show overflow, so it stays in a specified space on the page, as such:它只允许一行并且不显示溢出,因此它保留在页面上的指定空间中,如下所示:

<h2 id="element" contentEditable="true"></h2>

#element {
    white-space: nowrap;
    overflow: hidden;
}

The user can then edit the text and make it as long as they want.然后,用户可以编辑文本并根据需要制作文本。 Regardless of how much text the user has entered, I want the cursor to go back to the beginning of the text when they focus out of the header.无论用户输入了多少文本,我都希望光标在焦点离开标题时返回到文本的开头。 (This way, if they enter a bunch of text, they will always see the first part of it when they're not editing it). (这样,如果他们输入一堆文本,当他们不编辑时,他们总是会看到它的第一部分)。

I've tried the following ( home key keycode is 36), but I can't get the cursor to move back to the beginning of the element.我尝试了以下(键键码为 36),但无法让光标移回元素的开头。

var element = $('#element');

element.on('focusout', function() {
    var evt = $.Event('keydown', {keyCode: 36});
    element.trigger(evt);
});

Any ideas on getting the cursor back to the beginning of the element when I click out of it?当我点击它时让光标回到元素的开头有什么想法吗?

jQuery or vanilla are both fine. jQuery 或 vanilla 都很好。

A working (if not particularly good) solution to this is to just reset the html of the element when it is unfocused by using element.innerHTML = element.innerHTML;一个有效的(如果不是特别好)解决方案是在元素未聚焦时使用element.innerHTML = element.innerHTML;重置元素的 html element.innerHTML = element.innerHTML; . . Most browsers move the cursor back to the beginning when you do this.执行此操作时,大多数浏览器会将光标移回开头。 However, this is not a good idea if you have a lot of complicated markup in the element, as this causes everything to be repainted.但是,如果元素中有很多复杂的标记,这不是一个好主意,因为这会导致所有内容都重新绘制。

As @firefoxuser_1 mentioned, the thing to do is to re-set the inner html.正如@firefoxuser_1 提到的,要做的是重新设置内部html。 However, I found that I had to empty out the inner html, wait a dash, and then re-apply it.但是,我发现我必须清空内部html,等待一个破折号,然后重新应用它。 Example:例子:

var value = myElement.innerHTML;
myElement.innerHTML = '';
setTimeout(function() {
    myElement.innerHTML = value;
}, 1);

In jQuery.在 jQuery 中。 You can clone the current element.您可以克隆当前元素。 Add the clone after the original element and then remove it.在原始元素之后添加克隆,然后将其删除。

Here is an example:下面是一个例子:

// target is the editable div and clone is its copy
var target = $(".editableContent");
var clone = target.clone();
target.after(clone).remove();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM