在contentEditable< div>上设置光标位置 [英] Set cursor position on contentEditable <div>

查看:156
本文介绍了在contentEditable< div>上设置光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个contentEditable ='on'< div>重新获得焦点时,我在一个确定的,跨浏览器的解决方案中将光标/插入符号的位置设置到最后一个已知的位置。看来内容可编辑div的默认功能是在每次点击它时将光标/光标移动到div中文本的开头,这是不可取的。



我相信当他们离开div的焦点时,我将不得不在当前光标位置存储一个变量,然后在他们再次聚焦时再重新设置它,但是我无法将它们放在一起,或者找不到如果任何人有任何想法,工作代码片段或样本,我会很高兴看到他们。


$ b工作代码示例尚未。



$ b

我还没有任何代码,但这里是我所拥有的:

 <脚本类型= 文本/ JavaScript的 > 
// jQuery
$(document).ready(function(){
$('#area')。focus(function(){..} // focus我想象我需要

< / script>
< div id =areacontentEditable =true>< / div>

PS。我试过这个资源,但它似乎不适用于< div>。也许只适用于textarea(如何将光标移动到可用实体的结尾) em>

解决方案

这与基于标准的浏览器兼容,但可能会在IE中失败。一个起点IE不支持DOM范围。

  var editable = document.getElementById('editable'),
选择,范围;

//填充选择和范围变量
var captureSelection =函数(e){
//不要捕获edita之外的选择ble区域
var isOrContainsAnchor = false,
isOrContainsFocus = false,
sel = window.getSelection(),
parentAnchor = sel.anchorNode,
parentFocus = sel.focusNode ; (parentAnchor&& parentAnchor!= document.documentElement){
if(parentAnchor == editable){
isOrContainsAnchor = true;


}
parentAnchor = parentAnchor.parentNode; (parentFocus&& parentFocus!= document.documentElement){
}

if(parentFocus == editable){
isOrContainsFocus = true;
}
parentFocus = parentFocus.parentNode;
}

if(!isOrContainsAnchor ||!isOrContainsFocus){
return;
}

selection = window.getSelection();

//获取范围(标准)
if(selection.getRangeAt!== undefined){
range = selection.getRangeAt(0);

//获取范围(Safari 2)
} else if(
document.createRange&&
selection.anchorNode&&
selection.anchorOffset&&
selection.focusNode&&
selection.focusOffset
){
range = document.createRange();
range.setStart(selection.anchorNode,selection.anchorOffset);
range.setEnd(selection.focusNode,selection.focusOffset);
} else {
//此处失败,不由脚本的其余部分处理。
//可能是IE或者一些旧版浏览器
}
};

//输入
时重新计算选择editable.onkeyup = captureSelection;

//单击/拖拽选择后重新计算选择
editable.onmousedown = function(e){
editable.className = editable.className +'选择';
};
document.onmouseup = function(e){
if(editable.className.match(/ \sselecting(\s | $)/)){
editable.className = editable。 className.replace(/选择(\s | $)/,'');
captureSelection();
}
};

editable.onblur = function(e){
var cursorStart = document.createElement('span'),
collapsed = !! range.collapsed;

cursorStart.id ='cursorStart';
cursorStart.appendChild(document.createTextNode(' - '));

//插入开始游标标记
range.insertNode(cursorStart);

//如果选择了任何文本,插入结束游标标记
if(!collapsed){
var cursorEnd = document.createElement('span');
cursorEnd.id ='cursorEnd';
range.collapse();
range.insertNode(cursorEnd);
}
};

//将回调函数添加到afterFocus以在光标被替换后被调用
//如果您喜欢,这对于样式化按钮等将非常有用
var afterFocus = [] ;
editable.onfocus = function(e){
//稍微的延迟将避免初始选择
//(在开始或内容取决于浏览器)被误认为
setTimeout function(){
var cursorStart = document.getElementById('cursorStart'),
cursorEnd = document.getElementById('cursorEnd');

//不要做任何事(如果(cursorStart){
cursorStart.parentNode()){
.removeChild(cursorStart);
}
if(cursorEnd){
cursorEnd.parentNode.removeChild(cursorEnd);
}
} else if(cursorStart){
captureSelection();
var range = document.createRange();

if(cursorEnd){
range.setStartAfter(cursorStart);
range。 setEndB efore(cursorEnd);

//删除游标标记
cursorStart.parentNode.removeChild(cursorStart);
cursorEnd.parentNode.removeChild(cursorEnd);

//选择范围
selection.removeAllRanges();
selection.addRange(range);
} else {
range.selectNode(cursorStart);

//选择范围
selection.removeAllRanges();
selection.addRange(range);

//删除游标标记
document.execCommand('delete',false,null);



//在这里调用回调函数
for(var i = 0; i< afterFocus.length; i ++){
afterFocus [一世]();
}
afterFocus = [];

//再次注册选择
captureSelection();
},10);
};


I am after a definitive, cross-browser solution to set the cursor/caret position to the last known position when a contentEditable='on' <div> regains focus. It appears default functionality of a content editable div is to move the caret/cursor to the beginning of the text in the div each time you click on it, which is undesirable.

I believe I would have to store in a variable the current cursor position when they are leaving focus of the div, and then re-set this when they have focus inside again, but I have not been able to put together, or find a working code sample yet.

If anybody has any thoughts, working code snippets or samples I'd be happy to see them.

I don't really have any code yet but here is what I do have:

<script type="text/javascript">
// jQuery
$(document).ready(function() {
   $('#area').focus(function() { .. }  // focus I would imagine I need.
}
</script>
<div id="area" contentEditable="true"></div>

PS. I have tried this resource but it appears it does not work for a <div>. Perhaps only for textarea (How to move cursor to end of contenteditable entity)

解决方案

This is compatible with the standards-based browsers, but will probably fail in IE. I'm providing it as a starting point. IE doesn't support DOM Range.

var editable = document.getElementById('editable'),
    selection, range;

// Populates selection and range variables
var captureSelection = function(e) {
    // Don't capture selection outside editable region
    var isOrContainsAnchor = false,
        isOrContainsFocus = false,
        sel = window.getSelection(),
        parentAnchor = sel.anchorNode,
        parentFocus = sel.focusNode;

    while(parentAnchor && parentAnchor != document.documentElement) {
        if(parentAnchor == editable) {
            isOrContainsAnchor = true;
        }
        parentAnchor = parentAnchor.parentNode;
    }

    while(parentFocus && parentFocus != document.documentElement) {
        if(parentFocus == editable) {
            isOrContainsFocus = true;
        }
        parentFocus = parentFocus.parentNode;
    }

    if(!isOrContainsAnchor || !isOrContainsFocus) {
        return;
    }

    selection = window.getSelection();

    // Get range (standards)
    if(selection.getRangeAt !== undefined) {
        range = selection.getRangeAt(0);

    // Get range (Safari 2)
    } else if(
        document.createRange &&
        selection.anchorNode &&
        selection.anchorOffset &&
        selection.focusNode &&
        selection.focusOffset
    ) {
        range = document.createRange();
        range.setStart(selection.anchorNode, selection.anchorOffset);
        range.setEnd(selection.focusNode, selection.focusOffset);
    } else {
        // Failure here, not handled by the rest of the script.
        // Probably IE or some older browser
    }
};

// Recalculate selection while typing
editable.onkeyup = captureSelection;

// Recalculate selection after clicking/drag-selecting
editable.onmousedown = function(e) {
    editable.className = editable.className + ' selecting';
};
document.onmouseup = function(e) {
    if(editable.className.match(/\sselecting(\s|$)/)) {
        editable.className = editable.className.replace(/ selecting(\s|$)/, '');
        captureSelection();
    }
};

editable.onblur = function(e) {
    var cursorStart = document.createElement('span'),
        collapsed = !!range.collapsed;

    cursorStart.id = 'cursorStart';
    cursorStart.appendChild(document.createTextNode('—'));

    // Insert beginning cursor marker
    range.insertNode(cursorStart);

    // Insert end cursor marker if any text is selected
    if(!collapsed) {
        var cursorEnd = document.createElement('span');
        cursorEnd.id = 'cursorEnd';
        range.collapse();
        range.insertNode(cursorEnd);
    }
};

// Add callbacks to afterFocus to be called after cursor is replaced
// if you like, this would be useful for styling buttons and so on
var afterFocus = [];
editable.onfocus = function(e) {
    // Slight delay will avoid the initial selection
    // (at start or of contents depending on browser) being mistaken
    setTimeout(function() {
        var cursorStart = document.getElementById('cursorStart'),
            cursorEnd = document.getElementById('cursorEnd');

        // Don't do anything if user is creating a new selection
        if(editable.className.match(/\sselecting(\s|$)/)) {
            if(cursorStart) {
                cursorStart.parentNode.removeChild(cursorStart);
            }
            if(cursorEnd) {
                cursorEnd.parentNode.removeChild(cursorEnd);
            }
        } else if(cursorStart) {
            captureSelection();
            var range = document.createRange();

            if(cursorEnd) {
                range.setStartAfter(cursorStart);
                range.setEndBefore(cursorEnd);

                // Delete cursor markers
                cursorStart.parentNode.removeChild(cursorStart);
                cursorEnd.parentNode.removeChild(cursorEnd);

                // Select range
                selection.removeAllRanges();
                selection.addRange(range);
            } else {
                range.selectNode(cursorStart);

                // Select range
                selection.removeAllRanges();
                selection.addRange(range);

                // Delete cursor marker
                document.execCommand('delete', false, null);
            }
        }

        // Call callbacks here
        for(var i = 0; i < afterFocus.length; i++) {
            afterFocus[i]();
        }
        afterFocus = [];

        // Register selection again
        captureSelection();
    }, 10);
};

这篇关于在contentEditable&lt; div&gt;上设置光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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