我目前有一些按钮,当他们被按下时,字体颜色从灰色变为蓝色,我已经完成了这使用切换见下文。更改按钮上的背景图像按多个按钮
<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>
这取决于功能。你想要完成什么用例?需要有某种逻辑 – httpgio
因此,当点击棒球按钮时会发生什么? “baseballReg”类是否被删除?如果再次点击,是否应该加回去?你的问题不清楚。 – j08691
如果你想要更好的答案,花点时间让jsfiddle – vaskort