对于像按钮一样运作的插槽(例如,这个 Stack Overflow 页面侧栏上的按钮题为 问题、标签和用户)或选项卡,如果用户随机选择文本,则是否有 CSS 标准方式禁用突出效果?
我意识到可以用JavaScript做到这一点,而谷歌有点带来了Mozilla-only -moz-user-select选项。
有没有一个符合标准的方式来实现这一点与CSS,如果没有,什么是“最好的实践”方法?
对于像按钮一样运作的插槽(例如,这个 Stack Overflow 页面侧栏上的按钮题为 问题、标签和用户)或选项卡,如果用户随机选择文本,则是否有 CSS 标准方式禁用突出效果?
我意识到可以用JavaScript做到这一点,而谷歌有点带来了Mozilla-only -moz-user-select选项。
有没有一个符合标准的方式来实现这一点与CSS,如果没有,什么是“最好的实践”方法?
当前回答
使用SASS(SCSS合成)
你可以用混合物做到这一点:
// Disable selection
@mixin disable-selection {
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently supported by Chrome and Opera */
}
// No selectable element
.no-selectable {
@include disable-selection;
}
在HTML标签中:
<div class="no-selectable">TRY TO HIGHLIGHT. YOU CANNOT!</div>
在这个 CodePen 中尝试一下。
如果您正在使用 Autoprefixer,您可以删除其他预定。
浏览器兼容性在这里
其他回答
更好的是,您可以禁用文本选择。
如果你喜欢Sass(SCSS),而你不想使用Compass,你可以这样做:
风格.scss
@mixin user-select($select) {
-webkit-touch-callout:#{$select};
@each $pre in -webkit-, -moz-, -ms-, -o-, -khtml- {
#{$pre + user-select}: #{$select};
}
#{user-select}: #{$select};
}
.no-select {
@include user-select(none);
}
第一個方法:(完全無情):
.no-select::selection, .no-select *::selection {
background-color: Transparent;
}
.no-select { /* Sometimes I add this too. */
cursor: default;
}
<span>RixTheTyrunt is da best!</span>
<br>
<span class="no-select">RixTheTyrunt is da best!</span>
狙击:
.no-select::selection,.no-select *::selection {背景颜色:透明; }.no-select { /* 有时我也添加了这个。 */ cursor:默认; } <span>RixTheTyrunt是最好的!</span> <br> <span class="no-select">RixTheTyrunt是最好的!</span>
第二种方法(不含)
.no-select {
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
}
狙击:
.no-select { 用户选择: 无; -moz-用户选择: 无; -webkit-用户选择: 无; } <span>RixTheTyrunt 是最好的!</span> <br> <span class="no-select">RixTheTyrunt 是最好的!</span>
首先,解决问题,然后写代码,约翰·约翰逊
对于 Internet Explorer 的 JavaScript 解决方案是:
onselectstart="return false;"
试着使用这个:
::selection {
background: transparent;
}
如果您想指定不在特定元素中选择,则只需在选择规则之前设置元素类或ID,例如:
.ClassNAME::selection {
background: transparent;
}
#IdNAME::selection {
background: transparent;
}
更新2017年1月:
根据我可以使用,用户选择 + -webkit 用户选择为 Safari 足以实现所有主要浏览器所需的行为。
以下是所有可用的正确的CSS变量:
.noselect { _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
请注意,用户选择正在标准化过程中(目前在W3C工作草案中)。它不保证到处工作,浏览器之间可能存在实施差异。
更多信息可在 Mozilla Developer Network 文档中找到。
这个属性的价值是无,文本,条形,元素,元素,所有和继承。