用javascript使用css sprites

时间:2013-05-17 19:39:40

标签: javascript css-sprites

我知道如何使用纯html和css的css sprites。但是,如果我通过使用javascript从下拉框中选择一个值来进行dinamycally更改图像,该怎么办?

<select name="pricing" onchange="check_pricing();" id="pricing_value">
  <option value="">[Please Select]</option>
  <option value="Free" <?php if($pricing == 'Free'): ?> selected="selected"<?php endif; ?>>Free</option>
  <option value="Paid" <?php if($pricing == 'Paid'): ?> selected="selected"<?php endif; ?>>Paid</option>
</select>

function check_pricing() {
  var pricing = document.forms["MyForm"]["pricing_value"].value;
  if (pricing == 'Paid')
  {
    document.getElementById('table_drawad').style.backgroundImage="url('Images/drawad_bg_paid.png')";
  }
  else
  {
    document.getElementById('table_drawad').style.backgroundImage="url('Images/drawad_bg_free.png')";
  }

}

用css我会这样做:

table.table_drawad{
  width:120px;
  height:123px;
  background-image:url('Images/newcampaign_sprite2.png');
  background-position:0px 0px;
}

1 个答案:

答案 0 :(得分:0)

    .classA{
      width:120px;
      height:123px;
      background-image:url('Images/newcampaign_sprite2.png');
      background-position:0px 0px;
    }

    .classB{
      width:160px;
      height:145px;
      background-image:url('Images/newcampaign_sprite2.png');
      background-position:0px 0px;
    }

var elem = document.getElementById('table_drawad');
if (pricing == 'Paid')
  {
    elem.className = 'classB';
  }
  else
  {
     elem.className = 'classA';
  }