jquery自定义右键菜单、全选、不连续选择

2020-05-29 06:58:45易采站长站整理

<p>这是个div,这是个div,</p>
<p>这是个div,这是个div,</p>
<p>这是个div,这是个div,</p>
</div>

按住shift时,浏览器有默认的连选,先禁用掉:


.unselect{
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}

对于低版本的IE,利用selectstart事件:


$('#box')[0].onselectstart = function(e){
e.preventDefault();
return false;
};

给p注册click事件,同时要监听document对象的keydown和keyup事件:


$(document).keydown(function(e){
if(e.shiftKey){
shiftkey = 1;
}
}).keyup(function(){
shiftkey = 0;
});
$('#box').on('click','p',function(){
if(shiftkey === 1){
second = $(this).index();
for(var min = Math.min(first,second); min <= Math.max(first,second); min++){
$('#box').find('p').eq(min).css('color','red');
}
} else {
first = $(this).index();
$(this).css('color','red').siblings().css('color','black');
}
})

4、不连续选择
不连续选择需要监听ctrl键(mac下command键),同时给元素注册click事件。


$(document).keydown(function(e){
if(e.metaKey){ //win是e.ctrlKey
ctrlkey = 2;
}
}).keyup(function(){
ctrlkey = 0;
});
$('#box').on('click','p',function(){
if(ctrlkey === 2){
$(this).css('color','red');
} else {
$(this).css('color','red').siblings().css('color','black');
}
})