gpt4 book ai didi

改变背景图片的javascript函数

转载 作者:太空宇宙 更新时间:2023-11-04 00:12:44 25 4
gpt4 key购买 nike

我正在尝试编写一个 js 函数来更改由选择元素的 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>

最佳答案

在脚本中做如下修改,

  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
}

关于改变背景图片的javascript函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12470046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com