我目前有一些按鈕,當他們被按下時,字體顏色從灰色變爲藍色,我已經完成了這使用切換見下文。更改按鈕上的背景圖像按多個按鈕
<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