突出显示文本时如何禁用单击

时间:2019-06-27 14:28:45

标签: javascript events copy-paste highlight

我有一个用例,其中有一个带有可点击行元素的表。每行都有一些我想允许用户复制的文本。当我尝试突出显示文本时,我想防止发生click事件。

document.querySelector('tr').onclick = function () {
  window.alert(this.innerHTML);
}
table {
 border: 1px solid;
 margin-bottom: 10px;
}

td {
  padding: 10px;
}
<table>
  <tr>
   <td> This row is clickable </td>
  </tr>
</table>

<div>Try to highlight the text above by moving your cursor. I want to prevent click when you are trying to highlight the text which means you should not get the alert dialog.</div>

1 个答案:

答案 0 :(得分:0)

我认为那不是真的。.它主要用于禁用广播,复选框和其他...这是一些代码

代码1:

 <!DOCTYPE html>
<html>
<body>

Try to check this box: <input type="checkbox" id="myCheckbox">

<p>Toggling a checkbox is the default action of clicking on a checkbox. The 
preventDefault() method prevents this from happening.</p>

<script>
document.getElementById("myCheckbox").addEventListener("click", 
function(event){
  event.preventDefault()
});
 </script>

</body>
</html>

代码2:

      <!DOCTYPE html>
      <html>
      <body>

      <a id="myAnchor" href="https://w3schools.com/">Go to W3Schools.com</a>

      <p>The preventDefault() method will prevent the link above from following the URL.</p>

      <script>
      document.getElementById("myAnchor").addEventListener("click", function(event){
        event.preventDefault()
      });
      </script>

      </body>
      </html>