我正在尝试编写一个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>
答案 0 :(得分:1)
在changePic()
进行以下更正var square = document.getElementsByClassName("square");
,这将返回一个数组,其中包含css类为square
的所有元素,并且您需要更改此数组同样square[0].style.backgroundImage = selectBox.value;
用于更改具有此类的所有元素,您需要循环遍历数组,希望它有所帮助:)
答案 1 :(得分:1)
在脚本中进行以下更改
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
}