jQuery的选择从一个div然后更改CSS获得价值 [英] jQuery get value from select then change css of a div

查看:116
本文介绍了jQuery的选择从一个div然后更改CSS获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想用这个例子,但对我的生活我不能得到它的工作。结果
从选择事业部的更改背景

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

任何输入帮我相处移动将是非常美联社preciated

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搜索结果

bg = background.jpg
bg1 = background1.jpg
bg2 = background2.jpg

推荐答案

你是存储映射的方法是不是很灵活。我已存储他们作为一个对象。

The way you were storing the mappings wasn't very flexible. I have stored them as an object.

如果您将它们命名为 BG BG2 等,并没有他们的范围,你需要访问它们的窗口['保函'+ I] 这是混乱的。

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

另外,你可以存储在值的文件名每个选项元素的属性,只是分配和backgroundImage $(本).VAL()

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.

这篇关于jQuery的选择从一个div然后更改CSS获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆