2012-05-30 22 views
4

如何檢測用戶選擇(用鼠標突出顯示)是否在某個元素的子元素中?在html元素中檢測用戶選擇

實施例:

<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; 
+1

這可能會引發一些光http://stackoverflow.com/questions/6251937/how-to-get-selecteduser-highlighted-text-in-contenteditable-element-and-replac – Shyju

+1

由於您使用jQuery,[插頁](http://www.jquery-plugin.buss.hk/my-plugins/jquery-caret-plugin)非常酷。 – mayhewr

+0

任何人都可以幫忙嗎? – Sam

回答

2

使用jQuery on() event handler

$(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"); 
    }); 
});​ 

+0

我怎樣才能把它變成一個if函數? – Sam

+0

剛剛更新我的僞代碼 – Sam

+0

你想定義一些懸停區域,然後決定'如果'是子(0)返回true,否則如果子(1)返回false?類似的東西? –

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