簡體   English   中英

使用鍵 jquery 選擇文本的問題

[英]Issue with selecting text using keys jquery

我需要使用鍵和鼠標在 div 中突出顯示選定的文本。 使用鼠標進行選擇的方法如下:

html code:

 <div id="passage_response" contenteditable="true">
       <span class="word" num="0"> In </span>
       <span class="word" num="1"> this </span>
       <span class="word" num="2"> bug, </span>
       <span class="word" num="3"> issue </span>
       <span class="word" num="4"> no </span>
       <span class="word" num="5"> 1 </span>
       <span class="word" num="6"> explains </span>
    </div>

jquery:

    $('#passage_response .word').bind('dblclick', function() {
        toggleHighlight(this);
    });
    function toggleHighlight(target) {
        //highlighting functionality here
    }

這適用於鼠標雙擊。 但是對於使用密鑰,這不能按預期工作。 因為我需要讓視障人士可以使用此功能。 我嘗試使用 keypress 和 keydown 來使用鍵選擇文本。 但是對於 .word 類,它不會返回對象“this”。 請有人為此提出解決方案。 謝謝

為什么不直接在dblclicktoggle一個類?

我還為左右arrow keysshift key arrow keys組合添加了一個處理程序。

它檢查e.keyCode的左右箭頭值3739

然后它檢查e.shiftKey以查看是否按下了shift

 $('#passage_response .word').on('dblclick', function() { $('.word').removeClass('highlight'); $(this).addClass('highlight'); }); $(document).on('keyup',function(e){ e = e || window.event; switch(e.keyCode){ case 37: //LEFT ARROW if($('.word.highlight').length){ if(e.shiftKey){ //SHIFT + LEFT $('.word.highlight').last().removeClass('highlight'); }else{ //LEFT ONLY $('.word.highlight').removeClass('highlight').prev('.word').addClass('highlight'); } }else{ $('.word').eq(0).addClass('highlight'); } break; case 39: //RIGHT ARROW if($('.word.highlight').length){ if(e.shiftKey){ //RIGHT + SHIFT $('.word.highlight').last().next('.word').addClass('highlight'); }else{ //RIGHT ONLY $('.word.highlight').removeClass('highlight').next('.word').addClass('highlight'); } }else{ $('.word').eq(0).addClass('highlight'); } break; } });
 .highlight{ font-weight: bold; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="passage_response" contenteditable="true"> <span class="word" num="0"> In </span> <span class="word" num="1"> this </span> <span class="word" num="2"> bug, </span> <span class="word" num="3"> issue </span> <span class="word" num="4"> no </span> <span class="word" num="5"> 1 </span> <span class="word" num="6"> explains </span> </div>

 $('#passage_response .word').bind('dblclick', function() { $(this).css({"color":"blue"}); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="passage_response" contenteditable="true"> <span class="word" num="0"> In </span> <span class="word" num="1"> this </span> <span class="word" num="2"> bug, </span> <span class="word" num="3"> issue </span> <span class="word" num="4"> no </span> <span class="word" num="5"> 1 </span> <span class="word" num="6"> explains </span> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM