简体   繁体   中英

Make a div clickable and copyable?

As stated in the question, I have a div that I want to make clickable and copy-able?

to make the div copy-able, I simply do as following

<a href="/example.com">
  <div class="div">i contain some text</div>
</a>

But when trying to copy the text in that are inside of the div, the link gets clicked. What I want to do is that when clicking on the div, it should go to the url and that works. But I want also to make it possible to copy the text that is inside of the clickable div.

I prefer to fix the problem with html & css but even javascript is acceptable as last last resort.

This requires javascript, and we need 3 events to identify if the user is copying the text. Check out the snippet below, Let me know if it helps.

 class Box { constructor(target) { this.isUserCoping = false; this.isMouseClicked = false; this.handleMouseDown = this.handleMouseDown.bind(this) this.handleMouseMove = this.handleMouseMove.bind(this) this.handleMouseUp = this.handleMouseUp.bind(this) let $target = document.querySelector(target); $target.addEventListener('mousedown', this.handleMouseDown), $target.addEventListener('mousemove', this.handleMouseMove), $target.addEventListener('mouseup', this.handleMouseUp); } handleMouseDown() { this.isMouseClicked = true; } handleMouseMove() { this.isMouseClicked && (this.isUserCoping = true); this.isMouseClicked = false; } handleMouseUp(e) { !this.isUserCoping && this.navigate(e.target.dataset.href) console.log(this.isUserCoping); this.isUserCoping = false; console.log(this.isUserCoping); } navigate(href) { window.location.href = href; } } new Box('.js-div'); 
  <div class="js-div" data-href='https://www.google.com'>i contain some text</div> 

add following:

.div{
  display:inline-block
}

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