如何将活动按钮文字颜色更改为白色,并将其他按钮的文字颜色保持为黑色?
<button class="tablink tab" onclick="openPrices('Ladies', this, '#0b0c0d')" id="defaultOpen">Ladies services</button>
<button class="tablink tab1" onclick="openPrices('Mens', this, '#0b0c0d')">Mens services</button>
<button class="tablink tab2" onclick="openPrices('Colour', this, '#0b0c0d')">Colour services</button>
<script>
function openPrices(pricesName, elmnt, color) {
// Hide all elements with class="tabcontent" by default */
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Remove the background color of all tablinks/buttons
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
}
// Show the specific tab content
document.getElementById(pricesName).style.display = "block";
// Add the specific color to the button used to open the tab content
elmnt.style.backgroundColor = color;
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</script>
答案 0 :(得分:0)
通过javascript - &gt;
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
tablinks[i].style.color = "black";
}
elmnt.style.color = "white";
或通过CSS - &gt;
.tablink{
color:black;
}
.tablink.active {
color: white;
}
并在单击时向元素添加/删除活动类:
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
tablinks[i].classList.remove = "active";
}
elmnt.style.classList.add = "active";
或者第三个选项是使用link()而不是按钮,设置为按钮,并使用元素的不同css选择器(:active等)
答案 1 :(得分:0)
您可以同时使用CSS和Javascript,只需将:focus
用于CSS或使用:active
即可。 :focus
将保持颜色为白色,直到您点击为止,:active
只会在您主动点击按钮时保持颜色,我剪了一下你可以测试它。
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var button3 = document.getElementById("button3");
button1.onclick = function() {
button1.style.color = "#fff";
button2.style.color = "#000";
button3.style.color = "#000";
}
button2.onclick = function() {
button2.style.color = "#fff";
button1.style.color = "#000";
button3.style.color = "#000";
}
button3.onclick = function() {
button3.style.color = "#fff";
button1.style.color = "#000";
button2.style.color = "#000";
}
&#13;
<body>
<button type="button" class="btn" id="button1">Button1</button>
<button type="button" class="btn" id="button2">Button1</button>
<button type="button" class="btn" id="button3">Button1</button>
</body>
&#13;
或仅限CSS的方式
.btn {
color: #000;
}
.btn:focus {
color: #fff;
}
&#13;
<body>
<button type="button" class="btn" id="button1">Button1</button>
<button type="button" class="btn" id="button2">Button1</button>
<button type="button" class="btn" id="button3">Button1</button>
</body>
&#13;