检查光标是否在内容可编辑div的开头

时间:2016-04-21 09:32:38

标签: javascript

我想查找光标是否位于内容可编辑div的开头。我正在使用Internet Explorer 11.我有以下html并且我写了一个javascript,如果光标在开头则返回true。但我的代码总是返回“false”。请帮助我,当光标位于div的开头,即复选框之前,如何返回true。否则它应该返回false(即使光标在复选框之后)。

<!DOCTYPE>
<HTML>
<HEAD>
<script language="JavaScript">
function getSelectionTextDetail(element) {
    var atStart = false, atEnd = false;
    var selectionRange, temporaryRange;
    var selectedObject;
    if (window.getSelection) {
        selectedObject = window.getSelection();
        if (selectedObject.rangeCount) {
            selectionRange = selectedObject.getRangeAt(0);
            temporaryRange = selectionRange.cloneRange();
            temporaryRange.selectNodeContents(element);
            temporaryRange.setEnd(selectionRange.startContainer, selectionRange.startOffset);
            atStart = (temporaryRange.toString() === "");               
        }
    } 
    alert(atStart);
    //return atStart;
}
</script>
</HEAD>

<BODY>
<div style="border:solid 1px" contenteditable="true" onKeyUp="getSelectionTextDetail(this)">
<span style="font-family: Arial; font-size: 8pt;">
<input name="chk_O258" id="chk_O258" style="width: 12px; height: 12px; padding-top: 0px; padding-bottom: 0px; vertical-align: middle;" type="checkbox" value="on">Cursor Position Test</span></div>
</BODY>
</HTML>

1 个答案:

答案 0 :(得分:0)

Haven在IE中测试过,但试试这个:

<!DOCTYPE>
<HTML>
<HEAD>
<script language="JavaScript">
function getSelectionTextDetail(element) {
var atStart = false, atEnd = false;
var selectionRange, temporaryRange;
var selectedObject;
if (window.getSelection) {
    selectedObject = window.getSelection();

    if (selectedObject.rangeCount) {
        selectionRange = selectedObject.getRangeAt(0);
        temporaryRange = selectionRange.cloneRange();
        temporaryRange.selectNodeContents(element);
        temporaryRange.setEnd(selectionRange.startContainer, selectionRange.startOffset);
        check_string = temporaryRange.toString();
        atStart = (check_string.replace(/^\s+|\s+$/g, '') === "" && selectionRange.startOffset == 1);               
    }
} 
alert(atStart);
//return atStart;
}
</script>
</HEAD>

<BODY>
<div style="border:solid 1px" contenteditable="true" onKeyUp="getSelectionTextDetail(this)">
<span style="font-family: Arial; font-size: 8pt;">
<input name="chk_O258" id="chk_O258" style="width: 12px; height: 12px; padding-top: 0px; padding-bottom: 0px; vertical-align: middle;" type="checkbox" value="on">Cursor Position Test</span></div>
</BODY>
</HTML>