0

我正在尝试编写一个 js 函数来更改由 select 元素的 onchange() 函数触发的一类 html 元素的背景图像,但我似乎无法让它工作。这是我的js函数...

 function changePic() {
    var square = document.getElementByClass("square");
    var selectBox = document.getElementById("selectBox");
    var selectedItem = selectBox.options[selectBox.selectedIndex].value;
    square.style.backgroundImage = url(value);
}

...我的 CSS 课...

.square{
    border:2px solid black;
    position:absolute;
    width:100px;
    height:100px;
    cursor:pointer;
    background-image:url("house.jpg");
    color:red;
    font-size:32pt;
    font-family:Arial,Helvetica,sans-serif;
    text-align: center;
}

...以及 html 文件的相关部分...

    <div id="puzzle_container">
    <div class="square" id="puzzletile0"><p>1</p></div>
    <div class="square" id="puzzletile1"><p>2</p></div>
    <div class="square" id="puzzletile2"><p>3</p></div>
    <div class="square" id="puzzletile3"><p>4</p></div>
    <div class="square" id="puzzletile4"><p>5</p></div>
    <div class="square" id="puzzletile5"><p>6</p></div>
    <div class="square" id="puzzletile6"><p>7</p></div>
    <div class="square" id="puzzletile7"><p>8</p></div>
    <div class="square" id="puzzletile8"><p>9</p></div>
    <div class="square" id="puzzletile9"><p>10</p></div>
    <div class="square" id="puzzletile10"><p>11</p></div>
    <div class="square" id="puzzletile11"><p>12</p></div>
    <div class="square" id="puzzletile12"><p>13</p></div>
    <div class="square" id="puzzletile13"><p>14</p></div>
    <div class="square" id="puzzletile14"><p>15</p></div>
    <div class="square" id="puzzletile15"><p></p></div>
</div>
<input class = "button1" type="button" value = "Reset" onclick = "reset()" />
<input class = "button2" type="button" value = "Shuffle" onclick = "shuffle()" />
<br/>
<div id="picselect">
    Select an option to change background image
    <select id="selectBox" onchange="changePic();">
        <option value="Forest.jpg">Forest</option>
        <option value="House.jpg">House</option>
        <option value="Night.jpg">Night</option>
        <option value="City.jpg">City</option>
    </select>
</div>
4

2 回答 2

2

在脚本中进行以下更改,

  function changePic() {
        var square = document.getElementsByClassName("square");//had invalid markup
        var selectBox = document.getElementById("selectBox");
        var selectedItem = selectBox.options[selectBox.selectedIndex].value;
        square[0].style.backgroundImage  = "url("+selectedItem+")";//url should be inside quotes,added first element of the array
    }
于 2012-09-18T04:16:18.773 回答
0

在您changePic()进行以下更正var square = document.getElementsByClassName("square"); 时,这将返回一个包含所有具有 css 类的元素的数组,square并且作为一个数组,您还需要更改它以square[0].style.backgroundImage = selectBox.value; 更改具有此类的所有元素,您需要遍历数组希望能帮助到你 :)

于 2012-09-18T03:50:04.263 回答