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

前端 未结 2 941
北海茫月
北海茫月 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:45

    Based on the above answer, here's the vanilla version.

    document.addEventListener('click', function(){
        if (window.getSelection().anchorNode.parentElement.classList.contains('word')) {
        console.log('highlight');
        }
    });
    

    I would change 'document' to the wrapping container and 'word' to whatever class/ID is on the text you want to detect a highlight on.

    0 讨论(0)
  • 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') { ... }
    
    0 讨论(0)
提交回复
热议问题