如何让Chrome输入无法选择(但允许编辑)?

时间:2013-03-20 20:07:56

标签: javascript jquery html google-chrome cross-browser

代码:

(function($){
    $.fn.ctrl = function(key, callback) {
    if(typeof key != 'object') key = [key];
    callback = callback || function(){ return false; }
    return $(this).keydown(function(e) {
        var ret = true;
        $.each(key,function(i,k){
            if(e.keyCode == k.toUpperCase().charCodeAt(0) && e.ctrlKey) {
                ret = callback(e);
            }
        });
        return ret;
    });
};


$.fn.disableSelection = function() {
    $(window).ctrl(['a','s','c']);
    return this.each(function() {           
        $(this).attr('unselectable', 'on')
               .css({'-moz-user-select':'none',
                    '-o-user-select':'none',
                    '-khtml-user-select':'none',
                    '-webkit-user-select':'none',
                    '-ms-user-select':'none',
                    'user-select':'none'})
               .each(function() {
                    $(this).attr('unselectable','on')
                    .bind('selectstart',function(){ return false; });
               });
    });
};

})(jQuery);

$(document).ready(function(){
    $("textarea").on('focus',function(){
        $(this).disableSelection();
    });
});

小提琴:http://jsfiddle.net/EBhya/8/

背后的想法是用户可以键入,但不能突出显示文本。仍然可以使用箭头键进行更改等。

在Firefox和IE上,根据需要可以 100%

在Chrome上,可能在Safari上,当您专注于输入时,输入将被禁用,您甚至无法输入。

我已经尝试了从等待keydown应用禁用的选择到尝试监控鼠标点击和选择的所有内容。无论如何,如果有人可以提供帮助,我将非常感激。

1 个答案:

答案 0 :(得分:2)

正如bfavaretto建议的那样,这就是诀窍:https://stackoverflow.com/a/4656495/825789

相关问题