13

我有以下代码演示 contenteditable 属性和一个按钮,该按钮将在具有 contenteditable 区域的段落中注入粗体文本。我的问题是单击粗体后如何将焦点返回到我离开的位置,如果您突出显示某些文本,然后单击粗体,它会将这些文本加粗,但焦点将不再存在。如果您不选择任何内容并单击粗体,则会发生同样的事情,焦点将消失,如果您再次单击离开的位置,您可以输入粗体文本。

非常感谢您的帮助!

<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>
4

5 回答 5

9

你应该使用 .contents()

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

    $('#bold').click(function (){
            document.execCommand('bold', false, true);
            $(current).contents().focus();
    });
});
于 2010-07-22T02:56:35.803 回答
4

您可以只使用 jQuery .focus() 函数来聚焦它。这应该有效:

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

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

这只是在用户每次关注当前编辑字段时跟踪当前编辑字段,并且当单击粗体按钮时,焦点将设置回该字段。

于 2009-11-27T00:37:28.580 回答
1

您可能希望将最后单击的项目存储在变量中,然后在执行.execCommand后对其调用.focus()。我猜是这样的:

 $(function(){
        $('p.editable').click(function() {
            var clickedItem = $(this);
            clickedItem.attr('contenteditable', true).focus();
            $('#bold').click(function (){
                    document.execCommand('bold', false, true);
                    clickedItem.focus();
            });
        });
    });

这样,您还可以"contenteditable"从标记中删除属性...

高温高压

于 2009-09-11T11:55:14.400 回答
1

HTML:

<button onclick="doRichEditCommand('bold')" style="font-weight:bold;">B</button>

JavaScript:

function doRichEditCommand(aName, aArg){
    getIFrameDocument('editorWindow').execCommand(aName,false, aArg);
    document.getElementById('editorWindow').contentWindow.focus()
}

参考这可能会帮助你:

https://developer.mozilla.org/en/Rich-Text_Editing_in_Mozilla

于 2009-09-16T14:55:00.873 回答
0

如果您在 iframe 中,请在默认视图上调用 focus()。

myiframedocument.execCommand('Bold',false,null);
myiframedocument.defaultView.focus();
于 2012-01-18T00:29:08.730 回答