简体   繁体   中英

How to allow selecting text behind an absolutely positioned element, without using pointer-events:none

I have an HTML table with some text, where every row of the table should also be functions a link.

I do this by adding an absolutely positioned anchor element inside the <tr> , which has position: relative . This works very nicely, but the absolutely positioned <a> prevents the user from being able to select the underlying text to copy it to the clipboard.

I found a few answers suggesting adding pointer-events: none to the top element, which indeed works in the sense that the text underneath is selectable, but then this element stops reacting to all click events, and the link doesn't work.

Is there a way to make this work? Here's a simple version of my code, also on jsfiddle

 <table> <tbody> <tr style="position: relative"> <td> <a style="position: absolute; inset: 0; -webkit-user-drag: none;" href="#"></a> I want</td> <td>to be able</td> <td>to select this text</td> </tr> <tr style="position: relative"> <td> <a style="position: absolute; inset: 0; -webkit-user-drag: none; pointer-events: none" href="#"></a> This text is selectable </td> <td>but then the link</td> <td>doesn't work</td> </tr> </tbody> <table>

As soon as you introduce an anchor tag, you lose the ability to select the anchor text mid-way (you can still select the text if you begin the text selection prior to the start of the link).

Therefore, to allow mid-text selection, you need to detect a click, but reject the click if the mouse moves enough that it looks like text selection rather than a click.

 [...document.getElementsByClassName("tdlink")].forEach(e=>{ let clickStart = {x:0,y:0}; e.onmousedown = e=> Object.assign(clickStart,{x:e.clientX, y:e.clientY}); e.onclick = e=> Math.max(Math.abs(clickStart.xe.clientX), Math.abs(clickStart.ye.clientY))<3 && (Object.assign(clickStart,{x:0, y:0}), document.location.href = e.target.dataset.href); })
 .tdlink { cursor: pointer }
 <table> <tbody> <tr style="position: relative"> <td class="tdlink" data-href="https://wikipedia.org">The quick brown fox</td> </tr> </tbody> <table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM