0

好的,伙计们,所以我有这个算法,可以根据您按下的键(向上或向下箭头)选择一个选项。

var nr = 0;
    $(function(){
        $('#searchbox').keyup(function(e){
            var total = $('#suggest'+nr).attr("total");
            var code = (e.keyCode ? e.keyCode : e.which);
            if ( up(code) == 1 )
            {
                if (nr == 0)
                {
                        $('#suggest'+total).addClass('hlight');
                }
            }
            else
                if ( down(code) == 1 )
                {
                    $('#suggest'+nr).css({'background':'red'});;    
                }
        });

    });

但问题是,每次我释放相应的 div 时,都会通过更改背景颜色在几分之一秒内被选中,然后又恢复为原始背景颜色。

如何使它突出显示 div 和 css 以保持应用?谢谢你。

HTML:

<div id="search">
                <form action="home.php" method="get" name="search">
                   <input type="text" id="searchbox" name="srch" size="60" value="Search..." onFocus="if(this.value == 'Search...') {this.value = '';}" onBlur="if (this.value == '') {this.value = 'Search...';}" />
                   <input type='hidden' name='q' value='<?php echo $q; ?>' />
                   <input type='hidden' name='page' value='1' />
                  <button type="submit" id="searchb"><img src="pics/lens1.jpg" alt="Submit"></button>
                </form>

                </div><!--end search-->

PHP:

echo "<p class='suggestion' id=".$char." total=".($total-1)." style='color:black;font-size:13px;margin-bottom: 7px;'>".$id.",".$strg."</p>";

CSS:

<style >
.hlight{
    background:yellow;
}
​

</style>
4

1 回答 1

1

看看这里的关键功能:

http://jsfiddle.net/Mutmatt/mQahU/

var keyMap = {
    87: 'P1UP',
    83: 'P1DOWN',
    38: 'P2UP',
    40: 'P2DOWN'
},
    getKey = function(key) {
        return keyMap[(key.which || key.keyCode)] || '';
    };

$(document).keydown(function(event) {
        switch (getKey(event)) {
        case 'P1UP':
            event.preventDefault();
            keys['P1UP'] = true;
            break;
        case 'P1DOWN':
            event.preventDefault();
            keys['P1DOWN'] = true;
            break;
        case 'P2UP':
            event.preventDefault();
            keys['P2UP'] = true;
            break;
        case 'P2DOWN':
            event.preventDefault();
            keys['P2DOWN'] = true;
            break;
        default:
            break;
        }
    });

    $(document).keyup(function(event) {
        switch (getKey(event)) {
        case 'P1UP':
            event.preventDefault();
            delete keys['P1UP'];
            break;
        case 'P1DOWN':
            event.preventDefault();
            delete keys['P1DOWN'];
            break;
        case 'P2UP':
            event.preventDefault();
            delete keys['P2UP'];
            break;
        case 'P2DOWN':
            event.preventDefault();
            delete keys['P2DOWN'];
            break;
        default:
            break;
        }
    });

可能有帮助?

于 2012-10-02T19:06:45.167 回答