当用户选择文本时,我需要在执行最终任务之前检查两件事:
基本上:
HTML源代码:
<p>
<span id="subject-47" class="subject highlighted">Semencic credits his early familiarity with the breed to his own travels to South Africa<span class="count">4</span></span>, but especially to his frequent correspondence with the head of the first South African Boerboel club, one Mr. Kobus Rust. <strong>The Boerboel Breeders Association was established in 1983</strong> in the Senekal district of the Free State with the sole objective of ennobling and promoting the Boerboel as a unique South African dog breed.
</p>
我当前的Javascript(工作但我需要最后一次检查功能)
$( window ).load(function() {
$(document.body).bind('mouseup', function(e){
snapSelectionToWord();
var txt = getHTMLOfSelection();
var contentPos = $('.entry-content').html().indexOf( txt );
if( contentPos > 0 ) {
// do my thing here
// after I check txt IS NOT within a .highlighted css class
}
});
});
答案 0 :(得分:0)
我设法按照我想要的方式构建一个函数。
function isTextInClass( text, css_class ) {
var result = false;
$( '.highlighted' ).each( function( index ) {
if( $( this ).html().indexOf( text ) != 'undefined' ) {
var foundAt;
foundAt = $( this ).html().indexOf( text );
if( foundAt > 0 ) {
result = true;
}
}
});
return result;
}
答案 1 :(得分:0)
这是简短形式或答案。如果您使用Command + Shift + number 4
,它将为您提供突出显示文本的节点(外部元素)。我也会给你附上的id或类。基本上,如果您将上述代码段的结果存储在变量中,则可以分别使用window.getSelection().baseNode.parentNode
或id
来获取ID和类。
以下是示例代码 $(window).load(function(){
.className
答案 2 :(得分:0)
试试这段代码:https://jsfiddle.net/4pu6cbpo/
$(document.body).bind('mouseup', function(e){
//snapSelectionToWord();
var txt = getSelectionParentElement();
class_select = txt.getAttribute("class");
if(class_select !== null && class_select.indexOf("highlighted") > -1) {
alert("highlighted");
return false;
} else {
alert("NO highlighted");
return true;
}
/*
var contentPos = $('.entry-content').html().indexOf( txt );
if( contentPos > 0 ) {
// do my thing here
// after I check txt IS NOT within a .highlighted css class
}
*/
});
function getSelectionParentElement() {
var parentEl = null, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
parentEl = sel.getRangeAt(0).commonAncestorContainer;
if (parentEl.nodeType != 1) {
parentEl = parentEl.parentNode;
}
}
} else if ( (sel = document.selection) && sel.type != "Control") {
parentEl = sel.createRange().parentElement();
}
return parentEl;
}
如果所选文本突出显示的类的父标记类返回false。