5

如何检测用户选择(用鼠标突出显示)是否在某个元素的内部/子元素中?

例子:

<div id="parent">
   sdfsdf
   <div id="container">
       some 
      <span>content</span>
   </div>
   sdfsd
</div>

伪代码:

if window.getSelection().getRangeAt(0) is a child of #container
 return true;
else
 return false;
4

2 回答 2

2

使用 jQuery on() 事件处理程序

$(function() {
     $("#container > * ").on("click", 
         function(event){
            return true;
         });
     });​

编辑:http: //jsfiddle.net/9DMaG/1/

<div id="parent">outside
    <div id="container">
        outside
        <span>first_span_clickMe</span>
        <span>second_span_clickMe</span>
    </div>
 outside</div>


$(function() {
   $("#container > span").on("click", function(){
       $('body').append("<br/>child clicked");
   });
});​

​</p>

于 2012-05-30T03:41:03.013 回答
0

好的,我设法以“肮脏”的方式解决了这个问题。该代码可以使用改进,但它为我完成了这项工作,我现在懒得改变它。基本上,我遍历选择的对象,检查它是否在某个时候到达具有指定类的元素。

    var inArticle = false;
    // The class you want to check:
    var parentClass = "g-body"; 

    function checkParent(e){
        if(e.parentElement && e.parentElement != $('body')){
            if ($(e).hasClass(parentClass)) {
                inArticle = true;
                return true;
            }else{
                checkParent(e.parentElement);
            }
        }else{
            return false;
        }
    }


    $(document).on('mouseup', function(){
        // Check if there is a selection
        if(window.getSelection().type != "None"){
            // Check if the selection is collapsed
            if (!window.getSelection().getRangeAt(0).collapsed) {
                inArticle = false;

                // Check if selection has parent
                if (window.getSelection().getRangeAt(0).commonAncestorContainer.parentElement) {
                    // Pass the parent for checking
                    checkParent(window.getSelection().getRangeAt(0).commonAncestorContainer.parentElement);
                };


                if (inArticle === true) {
                    // If in element do something
                    alert("You have selected something in the target element");
                }
            };
        }
    });

JSFiddle

于 2014-05-09T18:54:22.107 回答