ser*_*nni 7 javascript events loops listener arrow-keys
对键盘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;
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下hovering
,ArrowDown
按下后跳转到列表中的最后一个元素.
如果break
取消注释,它会跳转到第二个元素并且不再跳跃.
无法得到原则,怎么做,听众总是听...
编辑
现场演示
或许,这是一个关闭的问题,但我不确定
在查看您的代码并意识到您想要做什么之后,我认为您的错误是substr
在您应该使用的地方使用了indexOf
. 这是更新后的行:
if (itemsContainer.getAttribute('class').indexOf('hovered') != -1)
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
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]
即可获取下一个兄弟姐妹。
归档时间: |
|
查看次数: |
1276 次 |
最近记录: |