我正在尝试编写一个 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>