javascript – 检测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;

最佳答案 使用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");
   });
});​

点赞