更改按钮上的背景图像按下多个按钮

时间:2014-02-12 14:07:46

标签: jquery css

我目前有一些按钮,当按下它们时,字体颜色从灰色变为蓝色,我已经使用切换完成了这一点,见下文。

<script>
 $( "button" ).click(function() {
  $( this ).toggleClass( "highlight" );
 });
</script>

问题是我需要更改背景图像,这是在多个按钮上。如何在不为每个按钮设置功能的情况下完成此操作?非常感谢任何帮助。

以下是完整代码:

<style>
 .sportsReg {width: 287px; height: 62px; border: solid 2px #2a2a2a; background-color: #303030; color: #bbbbbb; background-repeat: no-repeat; background-position: 21px; margin-right: 13px; margin-bottom: 13px;}
.footballReg {background-image:url('img/sports-icons/middle_grey_icons/americanfootball_grey.png');}
.footballRegColour {background-image:url('img/sports-icons/middle_grey_icons/americanfootball_colour.png');}
.baseballReg {background-image:url('img/sports-icons/middle_grey_icons/baseball_grey.png');}
.highlight {color: #1ab7ea !important;}
</style>

<script>
 $( "button" ).click(function() {
  $( this ).toggleClass( "highlight" );
 });
</script>

<button class="sportsReg footballReg">American Football</button>
<button class="sportsReg baseballReg">Baseball</button>

更新:该类应在.footballRegColour和.footballReg

之间切换

见下文:

<style>
.sportsReg {width: 287px; height: 62px; border: solid 2px #2a2a2a; background-color:    #303030; color: #bbbbbb; background-repeat: no-repeat; background-position: 21px; margin-  right: 13px; margin-bottom: 13px;}
.footballReg {background-image:url('img/sports-icons/middle_grey_icons/americanfootball_grey.png');}
.footballRegColour {background-image:url('img/sports-icons/middle_grey_icons/americanfootball_colour.png');}
.baseballReg {background-image:url('img/sports-icons/middle_grey_icons/baseball_grey.png');}
.baseballReg {background-image:url('img/sports-icons/middle_colour_icons/baseball_colour.png');}
.highlight {color: #1ab7ea !important;}
</style>

<script>
 $(document).ready(function(){
   $("button").click(function() {
   $( this ).toggleClass($(this).attr('toggleClass')));
 });
});
</script>

<button class="sportsReg footballReg" toggleClass="footballRegColour">American Football</button>
<button class="sportsReg baseballReg" toggleClass="baseballRegColour">Baseball</button>

请参阅小提琴:http://jsfiddle.net/gKHq5/

2 个答案:

答案 0 :(得分:0)

$('.sportsReg footballReg').click(function(){
    $(this).toggleClass('classname');
})

$('.sportsReg footballReg').click(function(){
    $(this).css({'background-image':'path'+$(this).text()});
})

如果文字Baseball也是您的图片Baseball.png

,则第二个功能可以自动执行此操作

答案 1 :(得分:0)

试一试:

<script>
 $(document).ready(function(){
   $("button").click(function() {
     $( this ).toggleClass($(this).attr('toggleClass'));
 });
});
</script>

<button class="sportsReg footballReg" toggleClass="footballReg">American Football</button>
<button class="sportsReg baseballReg" toggleClass="baseballReg">Baseball</button>

'ToggleClass'是将切换每个按钮的类

见这里:http://jsfiddle.net/gKHq5/2/