style.backgroundImage仅适用于Firefox

时间:2011-03-05 21:21:28

标签: javascript

我遇到了Javascript问题。我正在尝试在多选框中为选项设置背景图像。这适用于Firefox 3.6.14,但不适用于Internet Explorer 8.我已经制作了一个简短的代码示例来向您展示问题。有没有人能解决我的问题?

<html>
<head>
<script language="javascript" type="text/javascript">
    function changeIssueTypes(){
        var testSelect = document.getElementById("testSelect");
        var comboBoxTest = document.getElementById("comboBoxTest");

        testSelect.options.length = 0;
        if(comboBoxTest.value == 'optionTest1')
        {
            testSelect.options[0] = new Option();
            testSelect.options[0].value = 'testOption1';
            testSelect.options[0].innerHTML = 'Test option 1';
            testSelect.options[0].style.backgroundImage = 'url(http://www.multimove.nl/images/icons/small/icon_document.gif)';
            testSelect.options[0].style.backgroundRepeat = 'no-repeat';
        }
        if(comboBoxTest.value == 'optionTest2')
        {
            testSelect.options[0] = new Option();
            testSelect.options[0].value = 'testOption1';
            testSelect.options[0].innerHTML = 'Test option 1';
            testSelect.options[0].style.backgroundImage = 'url(http://www.middelburg.nl/static/middelburgpresentation/images/icons/icon_pdf.gif)';
            testSelect.options[0].style.backgroundRepeat = 'no-repeat';
        }
    }
</script>
</head>
<body>
<form>
    <select id="comboBoxTest" onchange="changeIssueTypes()">
        <option value="optionTest1" >Option test 1</option>
        <option value="optionTest2" >Option test 2</option>
    </select>
    <br/>
    <select multiple id="testSelect">
        <option value="initialOption">Test initial option</option>
    </select>
</form>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

首先:尝试直接在CSS中“手动”设置适当的CSS属性;我担心IE8不允许在多行选择框上更改background-image属性。

如果是这样,请尝试使用标准DOM方法(如appendChild()和createElement())来正确创建DOM元素:

    var opt = document.createElement("option");
    opt.value = "value";
    opt.innerHTML = "blah blah";
    opt.style.backgroundImage = "...";

    testSelect.appendChild(opt);