开发者

CSS on Mouse Down

Usually I would use :hover, but I want my website to be accessible on touchscreen media too.

I know I can use :active, but as soon as I let go of the mouse button, it goes back to its inactive state.

Effectively I want:

Mouse Down : Div goes green

Mouse Up: Div stays green开发者_如何学C

Mouse Down: Div goes red

Mouse Up: Div stays red

Instead of:

Mouse Down: Div goes green

Mouse Up: Div goes red


Without relying on jQuery:

The :active pseudo-class is used to apply css to elements while they're being clicked upon.

.button {
  color: red;
}
.button:active {
  color: green;
}


Here is how to do a pure css toggle 'button' (CSS3 required):

.toggle-button
{
  background-color: #FF0000;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
}

.toggle-box:checked + .toggle-button
{
  background-color: #00FF00;
}
<input type="checkbox" class="toggle-box" id="toggle-1" />
<label for="toggle-1" class="toggle-button">Click Me</label>

Of course, as always, IE fails at CSS (can't figure out the :checked pseudo-class), so you're probably better off just using JavaScript.


Use jQuery.

$(function(){
    $('#yo-content').click(function() { 
        $(this).toggleClass('make-me-green');
    });
});

CSS:

#yo-content { 
    background-color: #ff0000;
    cursor: pointer;
}

.make-me-green { 
    background-color: #33ff00 !important;
}

HTML:

<div id="yo-content">Feel free to click</div>


To my knowledge, there is no pure-CSS way of achieving what you effectively want.

But jQuery could come handy there...

 // let's suppose your div's (on page load) initial state is red (#F00), 
 // and this flag will stand for it
 var initialState = true; // setup a global state flag
 $("#foo").mousedown( function() { // on mousedown
   $(this).css("background-color", intialState ? "#0F0" : "#F00"); // toggle bgColor
   initialState = !initialState; // toggle flag
 });

Instead of setting css properties, you could set/add/remove classnames if you'd like the presentational aspects to stay as CSS-centric as possible (which is a decent perspective).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜