比方說,我有以下的HTML代碼:製作按鈕切換背景
<html>
<body>
<button id="one">Button 1</button>
<button id="two">Button 2</button>
<button id="reset">Reset</button>
</body>
</html>
我怎樣才能使按鈕從白色變成背景色爲綠色或白色到紅色,並點擊復位時使其改變背景顏色回到白色?
比方說,我有以下的HTML代碼:製作按鈕切換背景
<html>
<body>
<button id="one">Button 1</button>
<button id="two">Button 2</button>
<button id="reset">Reset</button>
</body>
</html>
我怎樣才能使按鈕從白色變成背景色爲綠色或白色到紅色,並點擊復位時使其改變背景顏色回到白色?
有一個CSS唯一方法,但使用它,我不會建議。你需要有一個div來佔用整個主體,幷包含你所有的內容,並有單選按鈕來存儲當前狀態。
body {
margin: 0;
height: 100vh;
width: 100vw;
}
[name=color] {
display: none;
}
#green[name=color]:checked~.background {
background: green;
}
#red[name=color]:checked~.background {
background: red;
}
#white[name=color]:checked~.background {
background: white;
}
.background {
height: 100%;
width: 100%
}
.button {
background-color: buttonface;
padding: 2px 6px 3px;
border-width: 2px;
border-style: outset;
border-color: buttonface;
}
.button:active {
border-style: inset
}
<input type="radio" name="color" id="green">
<input type="radio" name="color" id="red">
<input type="radio" name="color" id="white">
<div class="background">
<label class="button" for="green">Green</label>
<label class="button" for="red">Red</label>
<label class="button" for="white">White</label>
</div>
這僅僅是一個基本的實現,使之可行,你不得不把一些唱段的東西,使之符合A11Y。
謝謝你的幫助和遺憾,我一直沒有去。 –
不知道你想要的復位按鈕,但這裏一個jQuery腳本,將做的工作:
$("#one").click(function() {
$("body").css("background-color", "green");
});
$("#two").click(function() {
$("body").css("background-color", "red");
});
$("#reset").click(function() {
$("body").css("background-color", "white");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="one">Button 1</button>
<button id="two">Button 2</button>
<button id="reset">Reset</button>
你不能做你想做的純CSS
這裏是一個工作小提琴:
OP沒有特別要求jquery。可能是最好不要使用它 –
@PriyeshKumar問題編輯 –
[像這樣?](https://jsfiddle.net/bpsjns1a/) – Sank6
<button data-color="blue">Button 1</button>
<button data-color="red">Button 2</button>
<button data-color="white">Reset</button>
...
$('[data-color]').click(function(){
var color = $(this).data('color');
$('body').css('background-color',color);
});
ultimate。
使用JS。你的問題標籤只有HTML和CSS。這是隻能通過CSS來完成嗎? – andreim