You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mac Safari中如何让HTML元素彻底不可选择且无法被复制?

问题描述

给指定段落设置user-select:none等CSS属性后,Chrome和Firefox中该段落无法被选择复制,但Mac Safari浏览器存在异常:全选所有文本时,该段落看似未被选中,复制粘贴后却会出现其内容。

现有代码

CSS

#not_selectable {
    -webkit-tap-highlight-color:transparent;
    -webkit-touch-callout:none;
    -webkit-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select:none;
}

HTML

<p>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</p>

<p id="not_selectable">BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB</p>

<p>CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC</p>

解决方案

要在Safari中彻底禁止该元素被复制,需结合CSS与JavaScript处理,推荐以下方案:

方案1:监听copy事件过滤剪贴板内容

添加JavaScript代码,在复制触发时自动移除不可选元素的内容,不影响元素正常显示:

document.addEventListener('copy', function(e) {
    const forbiddenEl = document.getElementById('not_selectable');
    if (window.getSelection().containsNode(forbiddenEl, true)) {
        let selectedText = window.getSelection().toString();
        selectedText = selectedText.replace(forbiddenEl.textContent, '');
        e.clipboardData.setData('text/plain', selectedText);
        e.preventDefault();
    }
});

方案2:CSS增强限制(辅助方案)

在原有CSS基础上添加-webkit-user-modify: read-only;,可强化Safari下的选择限制,但需配合方案1使用以覆盖全选场景:

#not_selectable {
    -webkit-tap-highlight-color:transparent;
    -webkit-touch-callout:none;
    -webkit-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select:none;
    -webkit-user-modify: read-only;
}

内容的提问来源于stack exchange,提问作者David

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 15:45:32