7

有以下键盘ArrowDown事件监听器(它的关键代码是40):

window.onload = function() {    
var itemsContainer = document.getElementById('cities-drop');
document.addEventListener('keyup',function(event){
if (event.keyCode == 40 && itemsContainer.style.display=='block') {
event.preventDefault();
    for (var i=0;i<itemsContainer.children.length-1;i++){
        if (itemsContainer.getAttribute('class').substr('hovered')!=-1){
            itemsContainer.children[i].setAttribute('class','');
            itemsContainer.children[i].nextSibling.setAttribute('class','hovered');
                //break;
                }
            }
        }
    });

在这种情况下,按下hovering后跳转到列表中的最后一个元素。ArrowDown

如果break未注释,它会跳转到第二个元素并且不再跳转。

搞不懂原理,怎么办,那个听者一直在听……

也许编辑 现场演示
,这是一个关闭的问题,但我不确定

4

3 回答 3

4

在查看您的代码并意识到您要执行的操作后,我认为您的错误是 using substrwhere you should be using indexOf. 这是更新的行:

if (itemsContainer.getAttribute('class').indexOf('hovered') != -1)



更多细节: 您实际上在做的是使用substr带有字符串值的start索引。不确定结果是什么,但显然不是 -1,因为条件每次都返回 true,导致下一个元素每次都悬停,一直悬停到列表的底部。有了break语句,它在第一个元素处执行 if 语句(导致第二个元素“悬停”),然后退出。

在更正您的代码后,我会将break语句保留在那里,以便循环在找到匹配项后停止,并且不会不必要地循环遍历其余项目。


编辑:

我还在您的代码中发现了其他几个问题。这是一个至少在 IE 和 FF 中适用于我的示例(尚未在 Safari、Opera 或 Chrome 中测试):

<html>
<head>
    <style type="text/css">
        .hovered
        {
            color:red;
        }
    </style>
    <script type="text/JavaScript">
        function move(event)
        {
            var itemsContainer = document.getElementById('cities-drop');
            if (event.keyCode == 40 && itemsContainer.style.display == 'block')
            {
                if (event.preventDefault)
                    event.preventDefault();
                if (event.cancelBubble)
                    event.cancelBubble();
                if (event.stopImmediatePropagation)
                    event.stopImmediatePropagation();

                for (var i=0; i<itemsContainer.children.length-1; i++)
                {
                    if (itemsContainer.children[i].className.indexOf('hovered') != -1)
                    {
                        itemsContainer.children[i].className = "";
                        itemsContainer.children[i+1].className = "hovered";
                        break;
                    }
                }
            }
        };
    </script>
</head>
<body onkeydown="move(event)">
    <div id="cities-drop" style="display:block;">
        <p class="hovered">Item 1</p>
        <p>Item 2</p>
        <p>Item 3</p>
        <p>Item 4</p>
        <p>Item 5</p>
        <p>Item 6</p>
        <p>Item 7</p>
    </div>
</body>
</html>


详细信息:对我来说,在 IE9 中,该函数从未被调用过。相反,我只是将其设为常规函数并向标签添加了一个onkeydown事件。body

接下来,为了跨浏览器的兼容性,您应该在使用它之前检查以确保它event.preventDefault存在。我在 IE 中遇到 JS 错误。

在你的 if 语句中,你有itemsContainer.getAttribute('class'). 首先,您需要使用itemsContainer.children[i]. 其次,.getAttribute('class')在 IE 中对我不起作用,所以我将其切换为.className.

最后,itemsContainer.children[i].nextSibling对我不起作用,但它很简单,只需将其更改itemsContainer.children[i+1]为获取下一个兄弟姐妹。

于 2012-02-01T14:13:06.433 回答
3

我可以看到有几件事可能是个问题。首先,您更新 itemsContainer.children[i].nextSiblingwhich is itemsContainer.children[i+1]. 这就是为什么如果您跳过休息时间,它总是选择最后一个元素。itemsComtainer[i+1] 如果有与该类匹配的项目,将始终悬停。

第二个问题是 Travesty3 在他的回答中指出的。

我还更改了 if 条件以检查悬停的类是否在其中一个孩子上而不是容器本身上。

if (itemsContainer.children[i].getAttribute('class').match('hovered'))

我已经使用以下代码行修改了事件处理程序,这似乎工作正常:

document.addEventListener('keyup',function(event){
            if (event.keyCode === 40 && itemsContainer.style.display==='block') {
                event.preventDefault();
                for (var i=0,l=itemsContainer.children.length;i<l;++i){
                    if (itemsContainer.children[i].getAttribute('class').match('hovered')){
                        itemsContainer.children[i].setAttribute('class','');
                        itemsContainer.children[i+1].setAttribute('class','hovered');
                        break;
                    }
                }
            }
        });

请记住,制作这样的下拉控件需要做很多工作。用户希望使用键盘进行导航。为了获得出色的用户体验,您应该处理许多键,例如箭头键、用于聚焦控件的选项卡、用于打开和关闭它的空格、用于聚焦第一个匹配元素的字母数字输入等。

如果用户体验很重要,我建议为此使用框架和插件。我个人更喜欢 jquery 和 jquery ui,并且有许多用于选择下拉菜单的插件。另一个优点是,如果客户端禁用了 javascript,或者您的 javascript 由于某种原因会出错,大多数插件都会退回到常规的本机选择元素,该元素在功能上仍然可以正常工作。

我自己使用这个插件作为一个简单的下拉菜单: http ://www.abeautifulsite.net/blog/2011/01/jquery-selectbox-plugin/

编辑:我正在撤销这个建议,因为如果多个元素具有相同的名称,它就不起作用。如果这很重要,您应该查看 Filament Group 的 selectmenu 插件:http: //filamentgroup.com/lab/jquery_ui_selectmenu_an_aria_accessible_plugin_for_styling_a_html_select/ //编辑

...和组合框的 jquery 自动完成插件也支持书面输入:http: //jqueryui.com/demos/autocomplete/

于 2012-02-01T15:09:39.353 回答
3

您可以尝试一种更简单的方法,而不是使用循环:

window.onload = function() {    
    var itemsContainer = document.getElementById('cities-drop');

    document.addEventListener('keyup',function(event) {
        if (event.keyCode == 40 && itemsContainer.style.display=='block') {
            event.preventDefault();

            var previousHoveredChoice = itemsContainer.querySelector('.hovered');
            previousHoveredChoice.className = '';

            var currentHoveredChoice = previousHoveredChoice.nextSibling;
            if (currentHoveredChoice) {
                currentHoveredChoice.className = 'hovered';
            }
        }
    });

    //following code is copy-pasted from the live example 
    //just to close the onload function handler in this solution
    document.addEventListener('keyup',function(event){
        if (event.keyCode == 27) {

            if (document.getElementById('cities-drop').style.display=='block'){
                document.getElementById('cities-drop').style.display='none';
            }
        }

    });
    //end of copy-pasted code
};
于 2012-02-01T23:40:16.110 回答