如何禁用图像的高亮显示功能

30
我正在尝试禁用图片的高亮效果,当我将鼠标拖动到图片上时,它会被高亮显示。 看一下: enter image description here 非常感谢!

2
这是一些搜索结果中的顶部结果。我认为这个是你们许多人正在寻找的! - keyser
1
可能是禁用文本选择高亮的CSS规则的重复问题。 - showdev
9个回答

57

使用 user-select 属性:

img{
    -khtml-user-select: none;
    -o-user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    user-select: none;
}

1
我认为这是目前最干净的方法。同时,对于任何想要禁用图像中奇怪效果的人,可以查看 draggable 属性。在 img 标签中将其设置为 false 将避免用户意外(或非意外)拖动时出现幽灵图像。 - Herick

14
你可以尝试这个(这并不适用于所有浏览器):
img::-moz-selection {
    background-color: transparent;
    color: #000;
}

img::selection {
    background-color: transparent;
    color: #000;
}

或者您可以使用一个具有适当宽度和高度设置的 <div> 元素,并在其上使用 CSS 背景图像。例如,我在我的网站上使用了以下代码:

<div id="header"></div>

#header {
    height: 79px;
    width: 401px;
    background: url(http://nclabs.org/images/header.png) no-repeat;
}

最后,您可以使用JavaScript编程方式禁用它。


2019年已经到来,而选择伪类现在是最佳解决方案。 - Romain

11
img {
    -khtml-user-select: none;
    -o-user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    user-select: none;
}

@Phil 您可以编辑您的答案,这样它就不再是不正确的了。有关删除已接受答案以及为什么不应该删除的激烈讨论正在进行中。https://meta.stackoverflow.com/questions/272849/please-allow-me-to-delete-my-own-accepted-answer - tom_mai78101

6
这将禁用DOM元素的高亮显示:
function disableSelection(target){
    if (typeof target.onselectstart!="undefined") // if IE
        target.onselectstart=function(){return false}
    else if (typeof target.style.MozUserSelect!="undefined") // if Firefox
        target.style.MozUserSelect="none";
    else // others
        target.onmousedown=function(){return false;}

    target.style.cursor = "default";
}

这是使用方法:

disableSelection(document.getElementById("my_image"));

很棒的技巧,解决了Android WebView的问题。谢谢。 - Aung Aung Swe

4
尝试把它作为CSS背景而不是图像元素。

3
img{
   -ms-user-select: none;      /* IE 10+ */
   -moz-user-select: none;     /* Firefox all */
   -webkit-user-select: none;  /* Chrome all / Safari all */
   user-select: none;          /* Likely future */      
}

1
如果您在点击图片时遇到问题,这里提供解决方案。
img {
  -webkit-tap-highlight-color: transparent;
}

如果不起作用,请尝试在包含整个图像宽度的图像父级中进行操作。

1
使用body选择器可以从整个网站中删除文本和图像的选择。
body {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

0

如果这里有人对Sass mixin感兴趣:

// Prevent users to select an element
@mixin no-select {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接