我有一个Html编辑器,我想知道选定的文本是否填满了父代或父代有其他内容。 想这与HTML编辑器工具创建:如何知道选定的文本是否填满了父项?
<div>Hi this is <span>balh balh</span></div>
当用户选择blah blah
或Hi this is balh balh
短语,则必须检查true
,当用户选择is blah blah
短语,则必须检查false
。 我写了下面的代码它的工作。
$('#getSelection').click(function(){
var father = $(window.getSelection().focusNode.parentNode);
var hasFather = father[0].innerText === window.getSelection().toString();
alert(hasFather);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Hi this is <span>balh balh</span></div>
<input type="button" id="getSelection" value="Get Selection"/>
但当生成的HTML变得复杂它不工作。看到这个矛盾的样品(选择文本完全):
$('#getSelection').click(function(){
var father = $(window.getSelection().focusNode.parentNode);
var hasFather = father[0].innerText === window.getSelection().toString();
alert(hasFather);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="editable" contenteditable="TRUE" style="padding: 0px; color: rgb(0, 0, 0); font-family: Yekan; font-size: 12px; line-height: 20px; text-align: center; outline: -webkit-focus-ring-color auto 5px; border-color: rgb(204, 204, 204);"><div style="text-align: center;"><span style="font-style: italic; font-weight: bold; text-decoration: underline;"></span><span style="font-size: 13px;"><span style="font-size: 14px;"><span style="font-style: italic; font-weight: bold; text-decoration: underline;">blah blah blah blah blah </span><span style="font-style: italic; font-weight: bold;">blah </span><span style="font-style: italic; font-weight: bold; text-decoration: underline;">blah blah blah </span><span style="font-style: italic; font-weight: bold;">blah blah blah blah blah</span><span style="font-style: italic; font-weight: bold; text-decoration: underline;"> blah blah blah blah</span></span></span><span style="font-style: italic; font-weight: bold; text-decoration: underline;"></span></div></div>
<input type="button" id="getSelection" value="Get Selection"/>
如果选择下划线标记的内容,那么你看到你的答案无法正常工作。 –
是的,现在看。忘记为您的初始情况添加OR条件。我编辑了我的答案,现在应该工作。 –