您的位置:首页 > Web前端 > JavaScript

阻止元素被选中及清除选中的方法

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();}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息