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 に答える