Asa*_*vid 36 javascript jquery
我正在javascript中实现项目选择功能(使用jQuery).item是包含一些html的li.
用户可以单击一个项目(使其选中),然后按住Shift键并单击另一个项目以选择其中的所有项目.这基本上可以正常工作,但是shift-click也会选择(高亮显示)项目内显示的文本(移动点击的基本浏览器功能).有没有办法禁用它?
Roa*_*rth 40
尝试使用JavaScript和css的组合来防止首先选择:
$('li').attr('unselectable', 'on'); // IE
Run Code Online (Sandbox Code Playgroud)
css(对于不是IE的浏览器):
li {
user-select: none; /* CSS3 (little to no support) */
-ms-user-select: none; /* IE 10+ */
-moz-user-select: none; /* Gecko (Firefox) */
-webkit-user-select: none; /* Webkit (Safari, Chrome) */
}
Run Code Online (Sandbox Code Playgroud)
Jos*_*ola 39
Shift +单击后尝试此操作...
document.getSelection().removeAllRanges();
Run Code Online (Sandbox Code Playgroud)
如果这不够有效,您可能还必须取消onselectstart事件......
window.onload = function() {
document.onselectstart = function() {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
Ant*_*lls 28
我有这样的应用程序.特技是,我想允许选择,但我也想按住Ctrl键并按住Shift键点击选择项目.
我发现除了IE之外的所有人都允许你通过取消mousedown事件来击败这个,而在IE中最有效的方法是暂时禁用onselectstart:
$("#id").mousedown(function (e) {
if (e.ctrlKey || e.shiftKey) {
// For non-IE browsers
e.preventDefault();
// For IE
if ($.browser.msie) {
this.onselectstart = function () { return false; };
var me = this; // capture in a closure
window.setTimeout(function () { me.onselectstart = null; }, 0);
}
}
});
Run Code Online (Sandbox Code Playgroud)
此代码将仅在按下“shift”键期间停止文本选择,如果您松开它,则可以像往常一样选择文本。目前我正在使用这个 es6 代码。
["keyup","keydown"].forEach((event) => {
window.addEventListener(event, (e) => {
document.onselectstart = function() {
return !(e.key == "Shift" && e.shiftKey);
}
});
});
Run Code Online (Sandbox Code Playgroud)
如果表格行(项目)中有复选框,则只需在选择后将焦点设置为行的复选框即可.专注于复选框应该摆脱浏览器选择.您还可以专注于文本框或其他表单元素.对于JQuery,
$('tr').bind('click', function(e) {
// If shift key was down when the row was clicked
if (e.shiftKey) {
// Make the row selected
$(this).parent().children().slice($(last).index(), $(this).index()+1).addClass('selected').find('input:checkbox').attr('checked', true);
// Now focus on the checkbox within the row
$('input:checkbox', $(this)).focus();
}
});
Run Code Online (Sandbox Code Playgroud)