質問

I've created a number-only input validator for my app that's using KnockoutJS. When the user presses an illegal key (letter) I want the target input to flash the CSS animation on each illegal keypress. As it currently stands it just fires the animation once and I'm not sure why.

Example: http://codepen.io/anon/pen/oIamG/

Anyone any ideas?

役に立ちましたか?

解決

The problem is that you need to reset you CSS animation. In order to do that, you'd need to remove the animation and then add it again.
Move the -webkit-animation properties to the input like

input {
    border: 2px solid black;
    padding: 8px;
    /* 0.2s is used, just to see the effect, the animation needs to be  */
    -webkit-animation-duration: 0.2s;
    -webkit-animation-direction:forwards;
    -webkit-animation-timing-function:ease-in-out;
}

@-webkit-keyframes inputValidationBorder {
    0% { border: 2px solid red; }
    100% { border: 2px solid black; }
}

Then use the following binding:

ko.bindingHandlers.numeric = {
    init: function (element, valueAccessor) {
        $(element).bind('webkitAnimationEnd', function(){
            this.style.webkitAnimationName = '';
        });

        $(element).on('keydown', function (event) {
            // allow backspace, delete, tab, escape, enter/return and period.
            // if input is a letter then disable keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96    || event.keyCode > 105)) {
               element.style.webkitAnimationName= 'inputValidationBorder'; 
               event.preventDefault();
            }
        });
    }
};
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top