阻止元素被选中及清除选中的方法
2016-10-28 10:08
295 查看
有时候,我们希望阻止用户选中我们指定区域的文字或内容。有时候用户在一个区域执行频繁的点击操作,一不小心傲娇地点多了,就会选中当前区域的内容。制作轮播组件的时候,点击下一页,若点击的快的话,浏览器会识别为双击。双击的默认效果是选中整片区域,这时候轮播图组件就会被表示忧郁的蓝色幕布盖住,IE10+实现方式──CSS3
.unselect { -webkit-user-select: none; -moz-user-select: none; -khtml-user-select: none; -ms-user-select: none; /* 以下两个属性目前并未支持,写在这里为了减少风险 */ -o-user-select: none; user-select: none; }user-select: auto; => 用户可以选中元素中的内容user-select: none; => 用户不可选中元素中的内容user-select: text; => 用户可以选中元素中的文字目前这个 user-select 兼容 Chrome 6+、Firefox、IE 10+、Opera 15+、Safari 3.1+。ie5.5-9
<span unselectable="on"></span>由于unselectable属性不具有继承性,所以要遍历所有子元素并为各子元素添加该属性才有效。
// 将元素及其后代元素均设置为不可选择 var unselectable = function(root){ root.setAttribute('unselectable', 'on'); var descendant = root.getElementsByTagName("*"); var rTagName = /input|iframe|textarea|select/i; for (var i = 0, el; el = descendant[i++];){ if (!rTagName.test(el.tagName)){ el.setAttribute('unselectable', 'on'); } } };
使用 JS 阻止整个网页的内容被选中
document.body.onselectstart = function () { return false; }; // 或 document.body.onmousedown = function () { return false; }
阻止特定区域的内容被选中
var elem = document.getElementById('elemId');elem.onselectstart = function () {return false;};
使用 JS 清除选中
function clearSelections () {if (window.getSelector) {// 获取选中var selection = window.getSelection();// 清除选中selection.removeAllRanges();} else if (document.selection && document.selection.empty) {// 兼容 IE8 以下,但 IE9+ 以上同样可用document.selection.empty();// 或使用 clear() 方法// document.selection.clear();}}
相关文章推荐
- JS基础篇--JS与CSS阻止元素被选中及清除选中的方法总结
- 阻止元素被选中及清除选中的方法
- CSS 清除浮动元素方法 整理
- 清除浮动(闭合浮动元素)方法总结
- 禁止浏览器中双击选中元素的解决方法
- html页面中阻止用户选中、复制文本,阻止长按保存图片,阻止拖动元素等……
- 清除浮动——让包围元素包含浮动元素的四种方法
- CSS清除浮动元素方法
- img li 元素之间的间隙原因及清除方法
- 使用jQuery的data方法来为页面中的某个元素存储数据,(获取焦点,清除默认值)
- js如何知道checkbox是否被选中,并且选中的话让input元素变为不可编辑
- jquery阻止子元素触发父元素的事件的方法
- 关于css清除元素浮动的方法总结(overflow clear floatfix)
- WinForm中如何实现在一组RadioButton中清除选中的方法
- JQuery中的id选择器含有特殊字符时,不能选中dom元素的解决方法
- vector中清除某个元素方法(erase)
- ComboBox SelectionChanged改变SelectedItem MenuItem通过什么方法获得子元素选中项,已解决!
- jQuery获取选中内容及设置元素属性的方法
- 清除子元素浮动方法总结
- css清除浮动使父级元素展开的三个方法