I have been trying to ask this before, without any luck of explaining/proving a working example where the bug happens. So here is another try:

我之前一直在试着问这个问题,没有任何解释/证明bug发生的例子。这是另一个尝试:

I’m trying to replicate a placeholder effect on a contenteditable DIV. The core concept is simple:

我试图在contenteditable DIV上复制占位符效应。

<div contenteditable><em>Edit me</em></div>

<script>
$('div').focus(function() {
    $(this).empty();
});
</script>

This can sometomes work, but if the placeholder contains HTML, or if there some other processing being made, the editable DIV’s text caret is being removed, and the user must re-click the editable DIV to be able to start typing (even if it’s still in focus):

这可以起到一些作用,但是如果占位符包含HTML,或者正在进行其他处理,那么可编辑的DIV的文本插入符号将被删除,并且用户必须重新单击可编辑的DIV才能开始输入(即使它仍然处于焦点):

Example: http://jsfiddle.net/hHLXr/6/

例如:http://jsfiddle.net/hHLXr/6/

I can’t use a focus trigger in the handler, since it will create an event loop. So I need a way to re-set the caret cursor in the editable DIV, or in some other way re-focus.

我不能在处理程序中使用焦点触发器,因为它将创建一个事件循环。所以我需要一种方法来在可编辑的DIV中重新设置插入符号光标,或者以其他方式重新聚焦。

10 个解决方案

#1


23

You may need to manually update the selection. In IE, the focus event is too late, so I would suggest using the activate event instead. Here's some code that does the job in all major browsers, including IE <= 8 (which a CSS-only alternative will not):

您可能需要手动更新选择。在IE中,焦点事件太晚了,所以我建议使用activate事件。以下是一些在所有主要浏览器中都可以使用的代码,包括IE <= 8(只有css才能使用):

Live demo: http://jsfiddle.net/hHLXr/12/

现场演示:http://jsfiddle.net/hHLXr/12/

Code:

代码:

$('div').on('activate', function() {
    $(this).empty();
    var range, sel;
    if ( (sel = document.selection) && document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(this);
        range.select();
    }
});

$('div').focus(function() {
    if (this.hasChildNodes() && document.createRange && window.getSelection) {
        $(this).empty();
        var range = document.createRange();
        range.selectNodeContents(this);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
});

更多相关文章

  1. 如何在v模型更改时触发事件? (vue js)
  2. IronPython编辑器 —— FantasyPython雏形的雏形
  3. python模拟多次采样通过低概率事件多次重复实验趋近必然事件
  4. 支持c和python之间的跨语言(c)标记的代码编辑器
  5. 在管理页面中编辑M2M的两面
  6. 初学者的Selenium自动化测试指南,基于Python(五)——常用键盘事件
  7. 从django视图中的按钮获取click事件
  8. Telnet套接字网关到Coldfusion事件网关,连接到Asterisk AMI
  9. 我如何在Linux和Python中监听“usb设备插入”事件?

随机推荐

  1. android studio gradle编译时的jar冲突错
  2. android Rokon游戏引擎源码分享
  3. android textview 部分文字加颜色并可点
  4. Android图片圆角 用简单的方法实现
  5. android终端模拟器运行命令可以进行adb c
  6. Android(安卓)高手进阶教程(十三)之----A
  7. Android当导入项目时出现:ERROR: Your pro
  8. Android语音输入打字效果渐变以及纠错效
  9. android 日志文件输出
  10. android的常用控件总结【安卓入门五】