javascript - 使 div 可点击和可复制?

标签 javascript jquery html css

如问题中所述,我有一个 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/

相关文章:

javascript - 错误: Cannot read property 'checked' of undefined

JavaScript - 无法调用我的对象的方法

javascript - JavaScript 外部文件中的 PHP 语句

javascript - 在创建 Polymer 元素的模板之前导入 html 文件

javascript - 使用 Angular JS 将父 div 的焦点更改为子 href 元素的焦点

javascript - 在 jQuery 的 $.post 中调用函数时,未定义不是对象

javascript - 如何在 JavaScript 中为内容添加样式?

javascript - 播放带有播放和暂停动画的相应图像序列的音频

javascript - jQuery 中点击滚动菜单的小错误

python - 如何在 Django 中将基于函数的 View 集成到基于类的 View 中?