wordpress局部禁止复制代码

0
22

做一个复用的短代码(以后任意文章都能用),步骤如下:

一、把下面代码添加到主题的 functions.php

// [nocopy]这里放要保护的内容[/nocopy]
function qj_nocopy_shortcode($atts, $content = null) {
  $html = '
  <div class="no-copy-zone">'.$content.'</div>
  <style>
    .no-copy-zone {
      -webkit-user-select: none !important;
      -moz-user-select: none !important;
      -ms-user-select: none !important;
      user-select: none !important;
    }
    .no-copy-zone img { pointer-events: none; }
    /* 放开代码/表格的选择(可按需删除) */
    .no-copy-zone pre,
    .no-copy-zone code,
    .no-copy-zone table {
      -webkit-user-select: text !important;
      -moz-user-select: text !important;
      -ms-user-select: text !important;
      user-select: text !important;
      pointer-events: auto !important;
    }
  </style>
  <script>
  (function () {
    document.addEventListener("DOMContentLoaded", function(){
      document.querySelectorAll(".no-copy-zone").forEach(function(zone){
        zone.addEventListener("contextmenu", function(e){ e.preventDefault(); });
        ["copy","cut","dragstart"].forEach(function(evt){
          zone.addEventListener(evt, function(e){ e.preventDefault(); });
        });
        zone.addEventListener("keydown", function(e){
          const k = (e.key || "").toLowerCase();
          if ((e.ctrlKey || e.metaKey) && ["c","x","s","u","p","a"].includes(k)) {
            e.preventDefault();
          }
        });
        zone.addEventListener("selectstart", function(e){ e.preventDefault(); });
      });
    });
  })();
  </script>';
  return $html;
}
add_shortcode('nocopy', 'qj_nocopy_shortcode');

二、怎么使用

以后在任何文章里,用

[nocopy]
这里放需要保护的正文内容
[/nocopy]

只保护这段内容;不包裹的内容不受影响。

发布回复

请输入评论!
请输入你的名字