如何允许在禁止选择的帖子上选择一些文本

How to allow selecting some texts on the posts that are disabled from selecting?

本文关键字:选择 文本 何允许 禁止      更新时间:2023-09-26

我已经在StackExchange网站上问过这个问题。我在我的博客网站上添加了一个html/javascript代码,用于禁用内容复制。代码为:

<script src='demo-to-prevent-copy-paste-on-blogger_files/googleapis.js'></script><script type='text/javascript'> if(typeof document.onselectstart!="undefined" ) {document.onselectstart=new Function ("return false" ); } else{document.onmousedown=new Function ("return false" );document.onmouseup=new Function ("return false"); } </script>

如果我想允许只从页面中选择一些文本?例如,如果我想向读者提供一些代码,我如何允许他们只复制代码而不复制整个帖子?

提前感谢:)我的网站→www.aryanpoudel.com.np

首先,不能禁止从网站复制文本。所有文本都被发送到用户的浏览器,因此也可以被复制。这项措施只是不允许没有太多IT经验的用户不复制文本。

为了解决您的问题,最好使用CSS。有一个名为user-select的CSS属性可以设置为none。这不允许用户选择元素上的文本,属性设置为。请确保同时使用浏览器前缀进行用户选择,因为并非所有没有前缀的主要浏览器都支持该选项。

.element {
   -webkit-user-select: none;
   -moz-user-select: none;
   -ms-user-select: none;
   user-select: none;
}

您可以在此处找到浏览器兼容性:http://caniuse.com/#feat=user-不选择

如果只想让页面的一部分可选择,可以通过将用户选择属性添加到页面的body元素或*选择器来实现。如果您想让某些元素可选,只需重置CSS样式,将属性再次更改回user-select: text即可。

实现您想要的目标的另一种方法是:

function getSelectedText() {
  if (window.getSelection) {
    txt = window.getSelection();
  } else if (window.document.getSelection) {
    txt =window.document.getSelection();
  } else if (window.document.selection) {
    txt = window.document.selection.createRange().text;
  }
  return txt;
}
function removeSelection() {
  if (window.getSelection) {
    if (window.getSelection().empty) {
      window.getSelection().empty();
    } else if (window.getSelection().removeAllRanges) {
      window.getSelection().removeAllRanges();
    }
  } else if (document.selection) {
    document.selection.empty();
  }
}
var wordSelectables = ["number", "video", "computer"];
document.onmouseup = function() {
  var selText = getSelectedText().toString();
  if (wordSelectables.indexOf(selText) == -1) {
    removeSelection();
  }
}
number video <p>video</p>computer
<input value="videocomputer">