繁体   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