我正在寻找一种方法来检查特定的元素中是否选择了某些文本。
到目前为止,我所能找到的是一种使用window.getSelection
在整个文档中获取所选文本的方法。我想检查是否仅在#myDiv
中选择了某些文字。
如果在#myDiv
中选择了文本,则该函数应返回true。如果在其他地方选择了文本,或者没有选择文本,则该函数应返回false。
类似的东西:
$.fn.isTextSelected = function(method) {
return this[0].selectionEnd - this[0].selectionStart > 0 ? true : false;
}
$('#myDiv').isTextSelected();
我可以使用简单的jQuery方法吗?
答案 0 :(得分:2)
您可以查看commonAncestorContainer
获得的Range Object
的{{1}};
Selection.getRangeAt(0)

function isSelectionOnlyIn(yourDiv) {
var sel = window.getSelection();
if (sel.rangeCount < 1) return false;
var range = sel.getRangeAt(0);
if (range.collapsed) return false;
var cont = range.commonAncestorContainer;
return ($(cont) === $(yourDiv) || $(cont).parents(yourDiv).length > 0);
}
document.addEventListener('keydown', function() {
$('#result').text(isSelectionOnlyIn('#theOne'));
}, false);
&#13;
答案 1 :(得分:0)
你可以这样做:
$.fn.extend({
isTextSelected: function () {
var top = this.offset().top;
var bottom = this.offset().top + this.height();
console.log(window.getSelection());
if ( (selectionStart > top && selectionStart < bottom ||
selectionEnd > top && selectionEnd < bottom ||
selectionStart < top && selectionEnd > bottom ||
selectionEnd < top && selectionStart > bottom) &&
window.getSelection().type != "Caret" )
{
return true;
}
return false;
}
});
var selectionStart,
selectionEnd;
window.onmouseup = function (e) {
selectionEnd = e.pageY;
$("#result").html( $("#select").isTextSelected() );
}
window.onmousedown = function(e) {
selectionStart = e.pageY;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><div>Bacon ipsum dolor amet drumstick doner rump, venison spare ribs chicken short loin pork loin biltong bresaola shoulder ball tip. Sirloin pancetta cow t-bone chuck meatloaf tenderloin bacon. Shoulder beef jerky, pastrami sausage boudin hamburger t-bone landjaeger meatball pig. Sirloin swine cupim bacon cow. Picanha meatloaf kevin t-bone fatback shoulder.</div></div>
<br>
<br>
<div id="select">Boudin fatback salami chuck porchetta tongue tenderloin corned beef pork rump chicken tail leberkas hamburger picanha. Kielbasa sirloin jerky ball tip short ribs cow. Short loin andouille sausage filet mignon turducken pork chop tail tri-tip cow hamburger beef ribs corned beef t-bone meatloaf fatback. Ball tip doner hamburger, meatball meatloaf prosciutto pork belly drumstick leberkas turkey beef. Rump chuck ham pancetta boudin pork chop tri-tip tongue cupim.</div>
<br>
<br>
<div>Boudin ham hock venison shankle shoulder frankfurter porchetta tri-tip, jerky swine. Alcatra jerky swine short loin, strip steak boudin cupim ham ribeye turducken shankle t-bone venison. Salami biltong swine, short ribs ham doner bacon hamburger t-bone pork chop kielbasa ribeye tail pork short loin. Turkey frankfurter meatloaf sirloin brisket pancetta short loin, jowl flank ball tip pork loin bacon tri-tip.</div>
<br>
<br>
<br>
<br>
<div id="result"></div>
&#13;