用单选按钮更改背景图像

时间:2012-08-28 04:52:37

标签: jquery css

我想用单选按钮选择更改html的backgroundImage。每个单选按钮都有不同的图像。我尝试过这样:

      <input name="BG" id="wood" type="radio" value="" class="bgCollection" />
      <label for="radio">Wood</label>

      <input name="BG" id="steel" type="radio"  class="bgCollection"/>
      <label for="radio">Steel</label>

      <input name="BG" id="metal" type="radio" value="" class="bgCollection"/>
      <label for="radio">Black metal</label>

Jquery的:

    $(document).ready(function(){
            $(".bgCollection").change(
               function()
          {
        if($("input#wood").attr("checked"))  
                  {$("html").css('backgroundImage','url(../images/wood.jpg)');}
        if($("input#steel").attr("checked")
                   {$("html").css('backgroundImage','url(../images/BG-steel.jpg)');}
        if($("input#metal").attr("checked"))
                   {$("html").css('backgroundImage','url(images/blackMetal.jpg)');}
       });
  });

但这样背景并没有改变。

4 个答案:

答案 0 :(得分:3)

这里我已完成上述问题的完整演示。请查看演示链接。

演示: http://codebins.com/bin/4ldqp80

<强> HTML:

<input name="BG" id="wood" type="radio" value="" class="bgCollection" />
<label for="radio">
  Wood
</label>

<input name="BG" id="steel" type="radio"  class="bgCollection"/>
<label for="radio">
  Steel
</label>

<input name="BG" id="metal" type="radio" value="" class="bgCollection"/>
<label for="radio">
  Black metal
</label>

<强> jQuery的:

$(function() {
    $(".bgCollection").change(function() {
        if ($("#wood").is(":checked")) {
            $("body").css('backgroundImage', "url('http://cdnimg.visualizeus.com/thumbs/7f/78/gfx,wood-7f78592c9a6ed3390492c560c5ac6fec_h.jpg')");
        }
        if ($("#steel").is(":checked")) {
            $("body").css('backgroundImage', "url('http://www.aroorsteelcorporation.com/full-images/stainless-steel-834007.jpg')");
        }
        if ($("#metal").is(":checked")) {
            $("body").css('backgroundImage', "url('http://i00.i.aliimg.com/photo/v0/468538622/Brushed_metal_texture_prepainted_metal.jpg')");
        }
    });
});

演示: http://codebins.com/bin/4ldqp80

答案 1 :(得分:2)

你做得对,但你的jQuery中有一个小的语法错误

if($("input#steel").attr("checked")

if($("input#steel").attr("checked"))

请注意,最后缺少括号)

Working Fiddle

但更好的方法是使用此方法获取ID,然后应用开关检查值以设置背景

New Example

答案 2 :(得分:0)

代码中的第一个问题

你的第二个如果条件错误if($("input#steel").attr("checked") 这里应该是if($("input#steel").attr("checked"))你的闭括号 那么还有一件事你应该只改变下一个标签意味着控制而不是整个html。

所以在http://api.jquery.com/next/

使用jquery文档的.next()函数

我在jsfiddle测试中尝试了这段代码:http://jsfiddle.net/FB37y/

答案 3 :(得分:0)

代码的以下行中缺少:

if($("input#steel").attr("checked"))
                   {$("html").css('backgroundImage','url(../images/BG-steel.jpg)');} 
相关问题