你如何告诉如果大写锁定使用JavaScript?

但有一个警告:我做了谷歌,我能找到的最好的解决方案是附加一个onkeypress事件到每个输入,然后检查每次按下的字母是否大写,如果是,然后检查shift是否也按下。如果不是,那么caps lock必须是打开的。这感觉真的很脏,而且…浪费——肯定有比这更好的办法吗?


当前回答

反应

onKeyPress(event) { 
        let self = this;
        self.setState({
            capsLock: isCapsLockOn(self, event)
        });
    }

    onKeyUp(event) { 
        let self = this;
        let key = event.key;
        if( key === 'Shift') {
            self.shift = false;
        }
    }

    <div>
     <input name={this.props.name} onKeyDown={(e)=>this.onKeyPress(e)} onKeyUp={(e)=>this.onKeyUp(e)} onChange={this.props.onChange}/>
                {this.capsLockAlert()}
</div>

function isCapsLockOn(component, event) {
        let key = event.key;
        let keyCode = event.keyCode;

        component.lastKeyPressed = key;

        if( key === 'Shift') {
            component.shift = true;
        } 

        if (key === 'CapsLock') {
            let newCapsLockState = !component.state.capsLock;
            component.caps = newCapsLockState;
            return newCapsLockState;
        } else {
            if ((component.lastKeyPressed !== 'Shift' && (key === key.toUpperCase() && (keyCode >= 65 && keyCode <= 90)) && !component.shift) || component.caps ) {
                component.caps = true;
                return true;
            } else {
                component.caps = false;
                return false;
            }
        }
    }

其他回答

@user110902发布的这个基于jquery的回答对我很有用。然而,我对它进行了一些改进,以防止@B_N的评论中提到的缺陷:当你按Shift时,它无法检测到CapsLock:

$('#example').keypress(function(e) { 
    var s = String.fromCharCode( e.which );
    if (( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey )
    ||  ( s.toLowerCase() === s && s.toUpperCase() !== s && e.shiftKey )) {
        alert('caps is on');
    }
});

像这样,即使按下Shift,它也会工作。

这是一个自定义的jquery插件,使用jquery ui,由这个页面上的所有好主意和工具提示小部件组成。大写锁定消息是自动应用于所有密码框,不需要更改您当前的html。

自定义插件代码…

(function ($) {
    $.fn.capsLockAlert = function () {
        return this.each(function () {
            var capsLockOn = false;
            var t = $(this);
            var updateStatus = function () {
                if (capsLockOn) {
                    t.tooltip('open');
                } else {
                    t.tooltip('close');
                }
            }
            t.tooltip({
                items: "input",
                position: { my: "left top", at: "left bottom+10" },
                open: function (event, ui) {
                    ui.tooltip.css({ "min-width": "100px", "white-space": "nowrap" }).addClass('ui-state-error');
                    if (!capsLockOn) t.tooltip('close');
                },
                content: function () {
                    return $('<p style="white-space: nowrap;"/>')
                        .append($('<span class="ui-icon ui-icon-alert" style="display: inline-block; margin-right: 5px; vertical-align: text-top;" />'))
                        .append('Caps Lock On');
                }
            })
            .off("mouseover mouseout")
            .keydown(function (e) {
                if (e.keyCode !== 20) return;
                capsLockOn = !capsLockOn;
                updateStatus();
            })
            .keypress(function (e) {
                var kc = e.which; //get keycode

                var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
                var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
                if (!isUp && !isLow) return; //This isn't a character effected by caps lock

                // event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
                var isShift = (e.shiftKey) ? e.shiftKey : ((kc === 16) ? true : false); // shift is pressed

                // uppercase w/out shift or lowercase with shift == caps lock
                if ((isUp && !isShift) || (isLow && isShift)) {
                    capsLockOn = true;
                } else {
                    capsLockOn = false;
                }
                updateStatus();
            });
        });
    };
})(jQuery);

适用于所有密码元素…

$(function () {
    $(":password").capsLockAlert();
});

在JQuery。这涵盖了Firefox中的事件处理,并将检查意外的大写字母和小写字符。这预设了一个<input id="password" type="password" name="whatever"/>元素和一个id为'capsLockWarning'的单独元素,其中包含我们想要显示的警告(但否则将被隐藏)。

$('#password').keypress(function(e) {
    e = e || window.event;

    // An empty field resets the visibility.
    if (this.value === '') {
        $('#capsLockWarning').hide();
        return;
    }

    // We need alphabetic characters to make a match.
    var character = String.fromCharCode(e.keyCode || e.which);
    if (character.toUpperCase() === character.toLowerCase()) {
        return;
    }

    // SHIFT doesn't usually give us a lowercase character. Check for this
    // and for when we get a lowercase character when SHIFT is enabled. 
    if ((e.shiftKey && character.toLowerCase() === character) ||
        (!e.shiftKey && character.toUpperCase() === character)) {
        $('#capsLockWarning').show();
    } else {
        $('#capsLockWarning').hide();
    }
});

显示大写锁定状态的变量:

let isCapsLockOn = false;

document.addEventListener( 'keydown', function( event ) {
  var caps = event.getModifierState && event.getModifierState( 'CapsLock' );
  if(isCapsLockOn !== caps) isCapsLockOn = caps;
});

document.addEventListener( 'keyup', function( event ) {
  var caps = event.getModifierState && event.getModifierState( 'CapsLock' );
  if(isCapsLockOn !== caps) isCapsLockOn = caps;
});

适用于所有浏览器=> canIUse

反应

onKeyPress(event) { 
        let self = this;
        self.setState({
            capsLock: isCapsLockOn(self, event)
        });
    }

    onKeyUp(event) { 
        let self = this;
        let key = event.key;
        if( key === 'Shift') {
            self.shift = false;
        }
    }

    <div>
     <input name={this.props.name} onKeyDown={(e)=>this.onKeyPress(e)} onKeyUp={(e)=>this.onKeyUp(e)} onChange={this.props.onChange}/>
                {this.capsLockAlert()}
</div>

function isCapsLockOn(component, event) {
        let key = event.key;
        let keyCode = event.keyCode;

        component.lastKeyPressed = key;

        if( key === 'Shift') {
            component.shift = true;
        } 

        if (key === 'CapsLock') {
            let newCapsLockState = !component.state.capsLock;
            component.caps = newCapsLockState;
            return newCapsLockState;
        } else {
            if ((component.lastKeyPressed !== 'Shift' && (key === key.toUpperCase() && (keyCode >= 65 && keyCode <= 90)) && !component.shift) || component.caps ) {
                component.caps = true;
                return true;
            } else {
                component.caps = false;
                return false;
            }
        }
    }