How to check if text is highlighted (cross-browser)

前端 未结 2 961
北海茫月
北海茫月 2021-01-07 06:11

Is there a generic way in jQuery or JavaScript (most cross-browser compatible) to check if text has been highlighted?

I am working with an HTML

2条回答
  •  佛祖请我去吃肉
    2021-01-07 06:59

    You can use the Selection object :

    var selection = window.getSelection();
    

    See the documentation here : https://developer.mozilla.org/en-US/docs/Web/API/Selection

    With this object, you can check the selected dom node (anchorNode). For example :

    if ($(window.getSelection().anchorNode).attr('id') === 'something') { ... }
    

提交回复
热议问题