【问题标题】:Is it possible to prevent an image from being selected on a web page?是否可以防止在网页上选择图像?
【发布时间】:2014-12-03 05:25:24
【问题描述】:

我有一个显示表格的网站。表头包含文本描述和问号图像(用户可以将鼠标悬停在图像上以获得一些帮助)。

但我有一个请求,允许用户突出显示表格并在没有图像的情况下复制它(通过单击和拖动)。

这可能吗?我在这里尝试了建议

Preventing an image from being draggable or selectable without using JS

没有运气。

我可以将图像标记为“禁止复制”或“禁止选择”吗?

【问题讨论】:

  • @azrael 您可能需要考虑阅读整个问题而不仅仅是标题。然后你就会知道图像保护与 OP 无关。
  • 使用固定大小的divbackground-image 指向您的图像的css 属性代替img 标签。

标签: javascript html css


【解决方案1】:

防止使用 CSS 选择图像

img {
  user-select: none !important;
  -webkit-user-drag: none;
}

【讨论】:

    【解决方案2】:

    使用div 元素并使用background-image 属性将背景图像设置为div 元素的问号。

    div 元素不包含任何文本,因此无法选择。

    只是为了澄清:

    <thead>
      <tr>
        <th>header1</th>
        <th>header2 <div class="question-mark"></div></th>
      </tr>
    </thead>
    
    
    .question-mark{
        height: 100%;
        width: 10px;
        background-image: url("question_mark.png");
        background-repeat: no-repeat;
        background-size: contain;
        display: inline-block;
    }
    

    【讨论】:

    • 谢谢 - 效果非常好。我还添加了 display: inline-block;到 .question-mark 以防止 div 换行到表头中的新行。
    • 对不起,我遗漏了它,请随时编辑答案以改进。
    【解决方案3】:

    正如其他用户所建议的,您可以将 div 用作图像。

    但是,如果您希望将图像保留为图像,则可以使用

    var img = document.querySelector("#notToDragImg");
    img.onselectstart = function(){
                        return false;
                    };
    

    防止选择您的图像(并且不需要 jQuery)

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 2014-03-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      • 2020-07-16
      • 2011-02-13
      • 2012-08-13
      • 1970-01-01
      相关资源
      最近更新 更多