是否可以防止div中的mousedown竊取焦點,但允許在此容器中選擇文本(例如<div>
)?防止mousedown竊取當前輸入焦點,但允許選擇文本
/*// Version #1: Focus kept, but text is not selectable
$('div').on('mousedown', function(event) {
event.preventDefault();
});
/**/
// Version #2: Focus kept, text selectable, but focus is missing for a short time (flickering when css is applied to focused state)
$('div').on('mousedown', function(event) {
window.setTimeout(
function() {
$('input').focus();
}, 1
);
});
/**/
$('input').focus();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<div>A div container with some text, that should be selectable but not stealing focus of the input field</div>
我的第二個版本閃爍,只需點擊文本時(在目前的Chrome測試)。在Firefox中,選擇始終始於輸入字段。有沒有更好的解決方案?
以及爲什麼'window.setTimeout('?? – bipen
@bipen如果沒有setTimeout,文本將無法選擇,請嘗試在Chrome中使用此解決方案在Firefox中不起作用 – SuperNova