jQuery 从 select 获取值然后更改 div 的 css
我一直在尝试使用这个例子,但我一生都无法让它工作。
从选择中更改 Div 的背景
任何帮助我继续前进的输入都将是非常感谢
<script>
#changemybg {
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 =背景.jpg
bg1 = 背景1.jpg
bg2 = 背景2.jpg
I've been trying to use this example but for the life of me I cannot get it working.
Change background of Div from select
Any input to help me get moving along will be very appreciated
<script>
#changemybg {
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.jpg
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您存储映射的方式不是很灵活。我将它们存储为一个对象。
如果您将它们命名为
bg
、bg2
等,并且没有确定它们的范围,则需要通过window['bg' + i] 来访问它们
这很混乱。jsFiddle。
或者,您可以将文件名存储在每个
option
元素的value
属性中,然后简单地将backgroundImage
分配给$(this)。 val()。
另外,您尝试在
script
元素内设置样式。那是行不通的;你想要的是一个style
元素。The 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 aswindow['bg' + i]
which is messy.jsFiddle.
Alternatively, you could store the filename in the
value
attribute of eachoption
element and simply assign thebackgroundImage
to$(this).val()
.Also, you are trying to set styles inside a
script
element. That won't work; what you want is astyle
element.测试下面的代码:
并将您的选择更改为:
Test Below Code :
and Change your select to this :