2012-05-30 2 views
4

사용자 선택 (마우스로 강조 표시)이 특정 요소 내/하위 요소에 있는지 감지 할 수 있습니까?html 요소 내에서 사용자 선택 감지

예 :

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

의사 코드 : jQuery를 on() event handler를 사용

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를 사용하고 있으므로 [Caret] (http://www.jquery-plugin.buss.hk/my-plugins/jquery-caret-plugin)는 매우 멋지다. – mayhewr

+0

아무도 도와 줄 수 있습니까? – Sam

답변

2

$(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

을 업데이트했습니다. 일부 호버링 영역을 정의한 다음 'if'가 child (0)이면 true를 반환하고 'else if' false (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