我有一个简单的问题我目前正在开发一个带聊天系统的网站,我希望当用户从下拉框中选择特定的聊天室时,网站的背景图像会发生变化
以下是下拉列表选择的当前设置
<div class="container chat-signin">
<form class="form-signin">
<h2>Chat Login</h2>
<label for="nickname">Nickname</label> <input type="text" placeholder="Nickname" id="nickname">
<div>
<label for="chatroom">Chatroom</label> <select size="1" id="chatroom">
<option>Gaming Soc</option>
<option>Pokemon Soc</option>
</select>
</div>
<button type="submit" id="enterRoom">Sign in</button>
</form>
</div>
我认为可以使用jQuery完成,但在实现它时我感到很茫然
这是我尝试做的一个例子
如果用户选择Gaming Soc,则更改为背景1,如果他们选择Pookemon Soc则更改为背景2
任何帮助都很棒
答案 0 :(得分:2)
Javascript
var bgChange = function() {
var bgVal = $("#chatroom").val(), chatRoom = $("#chatRoom"); // chatRoom (chatRoom is object id)
if( bgVal == "1" ) {
chatRoom.css("background-image", "url(1.jpg)");
} else if( bgVal == "2" ){
chatRoom.css("background-image", "url(2.jpg)");
}
};
HTML
<select onchange="bgChange()" size="1" id="chatroom">
<option value="1">Gaming Soc</option>
<option value="2">Pokemon Soc</option>
</select>
答案 1 :(得分:1)
在此JS Fiddle中,您选择option
的值并从数组中选择相应的background-image
var bgArray = [
'//placehold.it/400x300?text=BG1',
'//placehold.it/400x300?text=BG2'
]
$('#chatroom').on('change', function() {
value = $(this).val() - 1;
$('#bgDiv').css({
'background-image': 'url(' + bgArray[value] + ')'
});
});
&#13;
#bgDiv {
width: 400px;
height: 300px;
outline: 1px dotted gray;
margin: 0 auto;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="container chat-signin">
<form class="form-signin">
<h2>Chat Login</h2>
<label for="nickname">Nickname</label>
<input type="text" placeholder="Nickname" id="nickname">
<div>
<label for="chatroom">Chatroom</label>
<select size="1" id="chatroom">
<option value="1">Gaming Soc</option>
<option value="2">Pokemon Soc</option>
</select>
</div>
<button type="submit" id="enterRoom">Sign in</button>
</form>
</div>
<!-- for demo only -->
<hr>
<div id="bgDiv"></div>
&#13;
答案 2 :(得分:0)
尝试使用background-image
处的多个css
属性来请求每个图片一次,将初始background-size
设置为0 0, 0 0
。如果select
option
selectedIndex
0
设为background-size
至100vw 100vh, 00
,则selectedIndex
为1
设为{{} 1}}到background-size
。
0 0, 100vw 100vh
&#13;
var arr = ["100vw 100vh, 0 0", "0 0, 100vw 100vh"];
$("#chatroom").change(function(e) {
$("body").css("backgroundSize", arr[this.selectedIndex])
})
&#13;
body {
background-image:url(http://lorempixel.com/400/300/technics)
, url(http://lorempixel.com/400/300/cats);
background-size: 0, 0;
background-repeat: no-repeat, no-repeat;
}
&#13;