Change background on button click, using CSS only?

早过忘川 提交于 2019-12-17 12:11:10

问题


Is it possible to change the background color on button click; of the entire document, using only CSS and HTML5?

(e.g.: it's trivial in JavaScript)


回答1:


Based on the fiddle I posted in the comments I've modified it very slightly to use the Bootstrap button CSS.

Just include Bootstrap's CSS file then use the code below.

HTML

<label for="check" class="btn btn-default">Toggle background colour</label>
<input type="checkbox" id="check" />
<div></div>

CSS

div {
    width: 100%;
    height: 100%;
    background: #5CB85C;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
}
label.btn {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 2; 
}
input[type="checkbox"]{
    display: none;
}
input[type="checkbox"]:checked + div{
    background: #5BC0DE;
}

This uses the adjacent sibling selector.

Here it is working: http://jsfiddle.net/eYgdm/ (I've added *-user-select: none; to prevent selection of the label text but it's not required for the label to work)

Browser support

Chrome, Firefox [Desktop & Mobile] (Gecko) ≥ 1.0, Internet Explorer ≥ 7, Opera ≥ 9 and Safari ≥ 3 References: Attribute selectors and Adjacent sibling selectors




回答2:


You could do something like this -- using the adjacent css selector :

<button class="btn">button</button>
<div class="content"></div>

btn:active + .content{
    background: blue;
}

http://jsfiddle.net/JeffreyTaylor/g47Uh/




回答3:


No, there's no concept of "click then do something" in CSS.




回答4:


Unfortunately, there's no backtracing in css rules; for a css selecter, there's no way to climb up an element's ancestors.




回答5:


You can (ab?)use the :target selector. This probably won't work in older browsers. Here's a super simple example I made that toggles the background when the link is clicked.

The concept is to apply CSS styling to targeted elements. In the code below, clicking the link will target the body's ID, which applies the style in body:target (changing the background color).

<html>
    <head>
        <style>
            body { background-color:#333; }
            body:target { background-color:#fff; }
        </style>
    </head>
    <body id="myBody">
        <a href="#myBody">Click</a>
    </body>
</html>

JSfiddle




回答6:


There is a way to do it:

.cc2:focus {
background-color: #19A3FF;}

The :focus basically means when you click on the element with the class cc2 it will turn it's background blue :) Hope that helps.



来源:https://stackoverflow.com/questions/19260401/change-background-on-button-click-using-css-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!