jQuery get value from select then change css of a div
I've been trying to use this example but for the life of me I cannot get it working.
Change background of Div from selectAny input to help me get moving along will be very appreciated
<script>
#changemy开发者_JAVA百科bg {
background: url(images/default.jpg) no-repeat 50% 50%;
}
</scipt>
<div id="changemybg"></div>
<select name="change" id="backgrounds">
<option>bg</option>
<option>bg1</option>
<option>bg2></option>
</select>
bg = background.jpg
bg1 = background1.jpg bg2 = background2.jpgThe way you were storing the mappings wasn't very flexible. I have stored them as an object.
If you named them bg
, bg2
, etc, and didn't scope them, you'd need to access them as window['bg' + i]
which is messy.
var bg = {
'bg': 'background.jpg',
'bg1': 'background1.jpg',
'bg2': 'background2.jpg'
};
$('#backgrounds').change(function() {
var background = $(this).find('option:selected').text();
if ( ! background in bg) {
return;
}
$('#changemybg').css({
'backgroundImage': 'url(' + bg[background] + ')'
});
});
jsFiddle.
Alternatively, you could store the filename in the value
attribute of each option
element and simply assign the backgroundImage
to $(this).val()
.
Also, you are trying to set styles inside a script
element. That won't work; what you want is a style
element.
Test Below Code :
$("#backgrounds").change(function()
{
var val = $(this).val();
$("#changemybg").css("background-image",val);
});
and Change your select to this :
<select name="change" id="backgrounds">
<option value="background1.jpg">bg</option>
<option value="background2.jpg">bg1</option>
<option value="background3.jpg">bg2></option>
</select>
精彩评论