简体   繁体   中英

jQuery onchange event does not fire when change initiated by keyboard arrows?

I'm using the jQuery below to change the font on a div element each time the onchange event fires for the select.

Trouble is, it does not work when I use the keyboard to cycle through the select list options.

It only fires when the select list is changed via mouseclick or letter click. How can I make it also respond to arrow up, down, right, left?

var changeHandler = function() {
    $('.fontPreview').fadeOut();
    var myFont = $('#myFonts :selected').val();
    var myFont2 = $('#myFonts :selected').val().split(':')[0];
    $('#fontPreviewSrc').attr('href','http://fonts.googleapis.com/css?family='+myFont);
    $('.fontPreview').attr('style','font-family:'+myFont2+';font-style:normal;font-size:2em;padding-top:10px;white-space:nowrap');
    $('.fontPreview').fadeIn(1500);
}

$("#myFonts").change(changeHandler).keypress(changeHandler);

I think you need something like this:

$(document).ready(function() {
    deflectEvent = function(event) {
        var listItemCount = $("#list1 > option").length - 1;
        var selectedItemIndex = $("#list1")[0].selectedIndex;
        if (event.which == $.ui.keyCode.UP) {
            $("#list1")[0].selectedIndex = (selectedItemIndex - 1 < 0) ? listItemCount : selectedItemIndex - 1;
        }
        if (event.which == $.ui.keyCode.DOWN) {
            $("#list1")[0].selectedIndex = (curListItem + 1 > noOfListItems) ? 0 : curListItem + 1;
        }
    }

    $(function($) { $("#input1").bind("keydown", deflectEvent) });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM