如问题中所述,我有一个 div 想要使其可点击和复制?
要使 div 可复制,我只需按照以下步骤操作
<a href="/example.com">
<div class="div">i contain some text</div>
</a>
但是,当尝试复制 div 内的文本时,链接会被点击。我想要做的是,当单击 div 时,它应该转到 url 并且可以正常工作。但我还希望能够复制可点击的 div 中的文本。
我更喜欢用 html 和 css 解决问题,但即使是 javascript 也可以作为最后的手段。
最佳答案
这需要 javascript,我们需要 3 个事件来识别用户是否正在复制文本。查看下面的代码片段,如果有帮助请告诉我。
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>
关于javascript - 使 div 可点击和可复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41201074/