jquery 在内容上设置光标位置可编辑< div>

q7solyqu  于 2023-02-21  发布在  jQuery
关注(0)|答案(9)|浏览(275)

我正在寻找一个明确的跨浏览器解决方案,当contentEditable ='on'重新获得焦点时,将光标/插入符号位置设置为最后一个已知位置。内容可编辑div的默认功能似乎是每次单击时将插入符号/光标移动到div中文本的开头,这是不可取的。
我相信当它们离开div焦点时,我必须将当前光标位置存储在一个变量中,然后当它们再次获得焦点时,重新设置此位置,但我还无法将其放在一起,或找到一个工作代码示例。
如果任何人有任何想法,工作代码片段或样本,我很乐意看到他们。
我真的没有任何代码,但这里是我有:

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

tmb3ates1#

此解决方案适用于所有主流浏览器:

saveSelection()附加到div的onmouseuponkeyup事件,并将选择保存到变量savedRange
restoreSelection()附加到div的onfocus事件,并重新选择保存在savedRange中的选择。
除非您希望在用户单击div时也恢复选择,否则这将非常有效(这有点不直观,因为通常您希望光标移动到您单击的位置,但为了完整性,包含了代码)
为了实现这一点,onclickonmousedown事件由cancelEvent()函数取消,cancelEvent()函数是一个跨浏览器函数,用于取消事件。cancelEvent()函数还运行restoreSelection()函数,因为在取消单击事件时,div不会接收焦点,因此除非运行此函数,否则不会选择任何内容。
变量isInFocus存储它是否处于焦点上,并被更改为“false”onblur和“true”onfocus。这允许仅在div未处于焦点上时取消单击事件(否则您将根本无法更改选择)。
如果您希望在通过单击聚焦div时更改所选内容,并且不恢复选择onclick(并且仅当使用document.getElementById("area").focus();或类似物编程地将焦点给予元素时,然后简单地移除onclickonmousedown事件。在这些情况下,也可以安全地删除onblur事件以及onDivBlur()cancelEvent()函数。
如果你想快速测试的话,直接把这段代码放到html页面的主体中应该可以工作:

<div id="area" style="width:300px;height:300px;" onblur="onDivBlur();" onmousedown="return cancelEvent(event);" onclick="return cancelEvent(event);" contentEditable="true" onmouseup="saveSelection();" onkeyup="saveSelection();" onfocus="restoreSelection();"></div>
<script type="text/javascript">
var savedRange,isInFocus;
function saveSelection()
{
    if(window.getSelection)//non IE Browsers
    {
        savedRange = window.getSelection().getRangeAt(0);
    }
    else if(document.selection)//IE
    { 
        savedRange = document.selection.createRange();  
    } 
}

function restoreSelection()
{
    isInFocus = true;
    document.getElementById("area").focus();
    if (savedRange != null) {
        if (window.getSelection)//non IE and there is already a selection
        {
            var s = window.getSelection();
            if (s.rangeCount > 0) 
                s.removeAllRanges();
            s.addRange(savedRange);
        }
        else if (document.createRange)//non IE and no selection
        {
            window.getSelection().addRange(savedRange);
        }
        else if (document.selection)//IE
        {
            savedRange.select();
        }
    }
}
//this part onwards is only needed if you want to restore selection onclick
var isInFocus = false;
function onDivBlur()
{
    isInFocus = false;
}

function cancelEvent(e)
{
    if (isInFocus == false && savedRange != null) {
        if (e && e.preventDefault) {
            //alert("FF");
            e.stopPropagation(); // DOM style (return false doesn't always work in FF)
            e.preventDefault();
        }
        else {
            window.event.cancelBubble = true;//IE stopPropagation
        }
        restoreSelection();
        return false; // false = IE style
    }
}
</script>
xdnvmnnf

xdnvmnnf2#

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

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);
};
eivnm1vs

eivnm1vs3#

    • 更新**

我编写了一个跨浏览器的范围和选择库Rangy,它包含了我下面发布的代码的改进版本。你可以使用selection save and restore module来回答这个问题,不过如果你在项目中没有做任何与选择相关的事情,也不需要这个库的大部分内容,我很想使用@Nico Burns的答案。

    • 上一个答案**

你可以使用IERange(http://code.google.com/p/ierange/)将IE的TextRange转换成类似DOM的Range,并将其与类似eyelidless的starting point的东西结合使用。就我个人而言,我只会使用IERange的算法来进行TextRange转换,而不是使用整个过程。IE的selection对象没有focusNode和anchorNode属性,但你应该可以只使用Range/<->从所选内容获取的TextRange。TextRange obtained from the selection instead.
我可能会把一些东西放在一起做这件事,将张贴回到这里,如果和当我这样做。
编辑:
我已经创建了一个脚本演示来实现这个功能。到目前为止,它在我尝试过的所有应用中都能正常工作,除了Opera 9中的一个bug,我还没有时间研究这个bug。它可以在IE 5.5、6和7、Chrome 2、Firefox 2、3和3.5以及Safari 4中工作,这些浏览器都是在Windows上运行的。
http://www.timdown.co.uk/code/selections/
注意,在浏览器中可以向后进行选择,这样焦点节点就位于选择的开始处,点击鼠标右键或左键会将插入符号移动到相对于选择开始处的位置。我认为在恢复选择时不可能重复这种情况,所以焦点节点总是位于选择的结束处。
我会在不久的某个时候把这篇文章写下来。

rjzwgtxy

rjzwgtxy4#

我有一个相关的情况,我特别需要将光标位置设置为contenteditable div的END。我不想使用像Rangy这样的成熟库,而且许多解决方案都太重了。
最后,我使用了这个简单的jQuery函数,将克拉位置设置为contenteditable div的末尾:

$.fn.focusEnd = function() {
    $(this).focus();
    var tmp = $('<span />').appendTo($(this)),
        node = tmp.get(0),
        range = null,
        sel = null;

    if (document.selection) {
        range = document.body.createTextRange();
        range.moveToElementText(node);
        range.select();
    } else if (window.getSelection) {
        range = document.createRange();
        range.selectNode(node);
        sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
    tmp.remove();
    return this;
}

理论很简单:在可编辑的末尾添加一个span,选择它,然后删除span --使光标位于div的末尾。您可以调整此解决方案,以便在任何需要的位置插入span,从而将光标置于特定位置。
用法很简单:

$('#editable').focusEnd();

就是这样!

xiozqbni

xiozqbni5#

我接受了Nico Burns的答案,并使用jQuery进行了计算:

  • 通用:对于每个div contentEditable="true"
  • 较短

You'll need jQuery 1.6 or higher:

savedRanges = new Object();
$('div[contenteditable="true"]').focus(function(){
    var s = window.getSelection();
    var t = $('div[contenteditable="true"]').index(this);
    if (typeof(savedRanges[t]) === "undefined"){
        savedRanges[t]= new Range();
    } else if(s.rangeCount > 0) {
        s.removeAllRanges();
        s.addRange(savedRanges[t]);
    }
}).bind("mouseup keyup",function(){
    var t = $('div[contenteditable="true"]').index(this);
    savedRanges[t] = window.getSelection().getRangeAt(0);
}).on("mousedown click",function(e){
    if(!$(this).is(":focus")){
        e.stopPropagation();
        e.preventDefault();
        $(this).focus();
    }
});

x一个一个一个一个x一个一个二个一个x一个一个三个一个

des4xlb0

des4xlb06#

在尝试了一下之后,我修改了上面的eyelidless的答案,并将其作为一个jQuery插件,这样您就可以执行以下操作之一:

var html = "The quick brown fox";
$div.html(html);

// Select at the text "quick":
$div.setContentEditableSelection(4, 5);

// Select at the beginning of the contenteditable div:
$div.setContentEditableSelection(0);

// Select at the end of the contenteditable div:
$div.setContentEditableSelection(html.length);

请原谅长代码帖子,但它可能会帮助一些人:

$.fn.setContentEditableSelection = function(position, length) {
    if (typeof(length) == "undefined") {
        length = 0;
    }

    return this.each(function() {
        var $this = $(this);
        var editable = this;
        var selection;
        var range;

        var html = $this.html();
        html = html.substring(0, position) +
            '<a id="cursorStart"></a>' +
            html.substring(position, position + length) +
            '<a id="cursorEnd"></a>' +
            html.substring(position + length, html.length);
        console.log(html);
        $this.html(html);

        // 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
            }
        };

        // Slight delay will avoid the initial selection
        // (at start or of contents depending on browser) being mistaken
        setTimeout(function() {
            var cursorStart = document.getElementById('cursorStart');
            var 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();
                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);
                }
            }

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

f45qwnt87#

您可以利用现代浏览器支持的selectNodeContents

var el = document.getElementById('idOfYoursContentEditable');
var selection = window.getSelection();
var range = document.createRange();
selection.removeAllRanges();
range.selectNodeContents(el);
range.collapse(false);
selection.addRange(range);
el.focus();
e5njpo68

e5njpo688#

在Firefox中,div的文本可能位于子节点(o_div.childNodes[0])中

var range = document.createRange();

range.setStart(o_div.childNodes[0],last_caret_pos);
range.setEnd(o_div.childNodes[0],last_caret_pos);
range.collapse(false);

var sel = window.getSelection(); 
sel.removeAllRanges();
sel.addRange(range);
pxiryf3j

pxiryf3j9#

我可能会在这个聚会上迟到,但是也许您可以将正在编辑的标记的当前值存储在一个变量中,而不是呈现给dom的值,而不是仅仅在前端操作dom。然后,您可以检测页面刷新并更改标记的innerHTML的值,或者在我的情况下,你只需要跟踪变化,并将其发送到后端。也许我的话不会做任何正义,所以我将写一个代码示例,为我的用例工作。

import React, { ChangeEvent, useEffect, useState } from "react";

interface IParentProps {}

const ParentComp: React.FC<IParentProps> = (props) => {
  const [innerValue, setInnerValue] = useState<string>();
  const [ghostValue, setGhostValue] = useState<string>();
  // create some boolean to detect when the enter key was pressed in the input field so that you
  //can remove the input field and add the child component
  const handleChange = (event: ChangeEvent<HTMLDivElement>) => {
    setInnerValue(event.currentTarget.innerHTML);
    setGhostValue(event.currentTarget.innerHTML);
  };

  const handleGhostChange = (event: ChangeEvent<HTMLDivElement>) => {
    setGhostValue(event.currentTarget.innerHTML);
  };

  //handle screen refresh, or send the ghost value to the backend
  useEffect(() => {}, []);

  return (
    <div>
      <input type="text" onChange={handleChange} />

      <ChildComponent handleChange={handleGhostChange}>
        {innerValue}
      </ChildComponent>
    </div>
  );
};

interface IChildProps {
  handleChange: (e: ChangeEvent<HTMLDivElement>) => void;
  children: React.ReactNode;
}

const ChildComponent: React.FC<IChildProps> = (props) => {
  return (
    <p
      contentEditable="true"
      suppressContentEditableWarning={true}
      onInput={props.handleChange}
    >
      {props.children}
    </p>
  );
};

我希望这是有意义的,如果你想让我修改的答案没有打字膨胀,我愿意和能够。如果这对你们的工作,请让我知道,我认为这是一个简单得多的解决方案,然后试图重新配置光标如何你想要的个人。

相关问题