举个栗子,有时候用户在一个区域执行频繁的点击操作,一不小心傲娇地点多了,就会选中当前区域的内容。
再举个栗子,制作轮播组件的时候,点击下一页,若点击的快的话,浏览器会识别为双击。
双击的默认效果是选中整片区域,这时候轮播图组件就会被表示忧郁的蓝色幕布盖住,多忧桑啊~
你看,这妹子多赞啊,可是你一紧张就乱点下一张的话,就变成酱紫了:
不过别怕,给这个现代化浏览器说好了咱不要这种忧桑色调就可以了:
.pretty-girl { -webkit-user-select: none; }
可是!可是!不是每个浏览器都可以不忧桑!!!那就只能请脚本大王出山了。
阻止选中
有时候,我们需要禁止用户选中一些文本区域,这时候可以直接通过让 onselectstart 事件 return false 来实现。即在body标签中添加如下:
<body onselectstart="return false">
使用 JS 阻止整个网页的内容被选中
document.body.onselectstart = function () { return false; }; // 或 document.body.onmousedown = ; }
阻止特定区域的内容被选中
var elem = document.getElementById('elemId'); elem.onselectstart = () { ; };
使用 CSS 控制样式阻止内容被选中
仅支持IE10及以上的高版本浏览器。IE9 以下请使用 onselectstart="return false;" 的方式来实现。
.unselect { none; -moz-user-select: -khtml-user-select: -ms-user-select: none; /* 以下两个属性目前并未支持,写在这里为了减少风险 */ -o-user-select: user-select: none; }
user-select: auto; => 用户可以选中元素中的内容
user-select: none; => 用户不可选中元素中的内容
user-select: text; => 用户可以选中元素中的文字
目前这个 user-select 兼容 Chrome 6+、Firefox、IE 10+、Opera 15+、Safari 3.1+。
需要注意的是,这个 user-select 还带浏览器厂商前缀,意味着她们还是非标准的,将来可能会改变。在生产环境中要慎用。
清除选中
有时候用户选中文字进行复制后,我们使用手动的方式进行选中的清除。
先来搞懂几个小知识点:
document.selection.createRange().text; IE9以下使用
window.getSelection().toString(); 其他浏览器使用
$('p').mouseup((){ var txt = window.getSelection ? window.getSelection().toString() : document.selection.createRange().text; alert(txt) ; })
2.取消处于选中状态的文字
document.selection.empty(); IE9以下使用
window.getSelection().removeAllRanges(); 其他浏览器使用
$('p').mouseup((){ window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); })
3.使某Dom中的文字处于选中状态
$('.somedom').click(this.focus(); if(window.getSelection){ var range=document.createRange(); range.selectNodeContents(); var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); } else (document.selection){ for ie document.body.createTextRange() range.moveToElementText() range.select(); } })
使用 JS 清除选中
clearSelections () { (window.getSelection) { 获取选中 window.getSelection(); 清除选中 selection.removeAllRanges(); } if (document.selection && document.selection.empty) { 兼容 IE8 以下,但 IE9+ 以上同样可用 document.selection.empty(); 或使用 clear() 方法 document.selection.clear(); } }
使用 CSS 清除选中
不考虑低版本 IE 的情况下,我们简单给选中元素添加以上 .unselect 的样式即可。
扩展onselect 事件
定义与用法:onselect 事件会在文本框中的文本被选中时发生。
语法:
onselect="SomeJavaScriptCode"
其中参数SomeJavaScriptCode为必需。规定该事件发生时执行的 JavaScript。
input type="text">,textarea>
支持该事件的 JavaScript 对象:window
实例1
在本例中,当用户试图选择文本框中的文本时,会显示一个对话框:
form> Select text: ="text" value="Hello world!" onselect="alert('You have selected some of the text.')" /> br /></> Select text: textarea cols="20" rows="5"="alert('You have selected some of the text.')" Hello world!</> >
实例2
="选中的内容" id/>
JS方法:
var text = document.querySelector('#text'); text.addEventListener('select',1)">(e){ console.log(e.target.value); 选中的内容 })
参考
https://segmentfault.com/a/1190000000638651