使用javascript聚焦在一个选择内部?

时间:2012-03-21 13:49:57

标签: javascript internet-explorer windows-ce

以下代码在大多数浏览器中都能正常工作,但它在Internet Explorer CE Mobil中无效,我不能为我的生活找出原因。

function autofocus() {
    var el = document.getElementById("autofocus");
    if (el === null) {
        return;
    } else if (el.tagName.toUpperCase() == "SELECT") {
        if (el.selectedIndex == -1) {
            el.options[0].selected = true;

        }
    }
    el.focus();
}

$(window).ready(function () {
    autofocus();  
});​

它在我尝试的所有常规浏览器中都能很好地工作,但在Internet Explorer Mobile中它似乎专注于选择列表本身,这意味着无法在不单击一个选项的情况下导航各种选项。也许如果我点击其中一个选项呢?有关不起作用的示例,请参阅http://jsfiddle.net/mhenrixon/sbwCv/19/

编辑:它与selectedIndex本身没有关系,因为大多数时候会有一个selectedIndex,如15,5,27或其他。只是不-1。

2 个答案:

答案 0 :(得分:1)

在我的三星传奇上,我正在跑步:

Mozilla / 4.0(兼容; MSIE 6.0; Windows CE; IEMobile 7.11)VZW:SCH-i770 PPC 320x320

此浏览器的问题是jQuery ready函数。

如果您使用<body onload="autofocus()">,则<select>将选择其第一个选项。而这个选择确实很有针对性;如果我使用光学鼠标,我可以右箭头选择不同的选项和空格键来选择它。

所以这是我最终得到的测试用例:

<html>
<head>
<title>Test</title>
<!-- script type="text/javascript" src="jquery-1.4.2.js" -->
<script type="text/javascript">
function autofocus() {
    var el = document.getElementById("autofocus");
    if (el === null) {
        return;
    } else if (el.tagName.toUpperCase() == "SELECT") {
        if (el.selectedIndex == -1) {
            el.options[0].selected = true;
        }
    }
    el.focus();
}

/*
$(window).ready(function () {
    autofocus();  
});
*/
</script>
</head>
<body onload="autofocus()">
<select autofocus="autofocus" id="autofocus" multiple="multiple">
    <option value="0">0:17,00st</option>
    <option value="P11">P11:1918,00st</option>
    <option value="P12">P12:100,00st</option>
</select>
</body>
</html>

当然它也适用于桌面浏览器。

答案 1 :(得分:0)

你可以试试el.selectedIndex = 2;是否有效,我似乎无法在IE8中重现这个问题,所以问题可能与IE CE Mobile有关

function autofocus() {
    var el = document.getElementById("autofocus");
    if (el === null) {
        return;
    } else if (el.tagName.toUpperCase() == "SELECT") {
        if (el.selectedIndex == -1) {
            el.selectedIndex = 0;
            el.options[0].selected = true;
        }
    }
    el.focus();
}

$(window).ready(function () {
    autofocus();  
});