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

前端 未结 2 943
北海茫月
北海茫月 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.

提交回复
热议问题