在execCommand之后将焦点返回到contenteditable吗? [英] return focus to contenteditable after execCommand?

查看:86
本文介绍了在execCommand之后将焦点返回到contenteditable吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码演示了contenteditable属性和一个按钮,该按钮会将粗体文本插入具有contenteditable区域的段落中.我的问题是如何将焦点恢复到单击粗体后我离开的地方,如果突出显示一些文本,然后单击粗体,它将使那些文本变为粗体,但是焦点将不再存在.如果您不选择任何内容并单击粗体,则会发生相同的情况,焦点将消失,如果再次单击中断的位置,则可以键入粗体文本.

I have the following code demonstrating contenteditable property and a button that will inject bold text into the paragraph with contenteditable area. My question is how to return focus to where i left off after clicking on bold, if you highlight some text, and click bold, it'll bold those text, but the focus will not be there anymore. Same thing happens if you don't select anything and click bold, the focus will be gone and if you click where you left off again, you can type bold texts.

非常感谢您的帮助!

<head>
    <style type="text/css">
    #container{
        width:500;
    }
    .handle{
        float:left;
    }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
    <script type="text/javascript">
    $(function(){
        $('#bold').click(function (){
            document.execCommand('bold', false, true);
        });
    });
    </script>
</head>
<button id="bold">Bold</button>
<div id="container">
<div class="c"><p contenteditable>Some text here asdf asdf asdf asdf asdf asd fasd fsa dfsa df asdf sadf sa dfa sdf sadf asd fsa df sadf asdf asdf asd fas df asdf as </p></div>

<div class="c"><p contenteditable>Some text here asdf asdf asdf asdf asdf asd fasd fsa dfsa df asdf sadf sa dfa sdf sadf asd fsa df sadf asdf asdf asd fas df asdf as </p></div>
</div>

推荐答案

您应该使用.contents()

YOU SHOULD USE .contents()

var current;
$(function(){
    $("p[contenteditable]").focus(function() {
        current = this;
    });

    $('#bold').click(function (){
            document.execCommand('bold', false, true);
            $(current).contents().focus();
    });
});

这篇关于在execCommand之后将焦点返回到contenteditable吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆