Hover, Hover-out, Cicked
$('#box_1, #box_2, #box开发者_JS百科_3, #box_4').hover(function() {
$(this).addClass('hover');
}, function() {
$(this).removeClass('hover');
});
But when I clicked, "HOVER
" class = .removeClass('hover')
Anyway to stay this "HOVER
" class when I clicked ?
http://jsfiddle.net/EAa6p/ (This is my original)
DONE ! by Ben <3 http://jsfiddle.net/EAa6p/1/ Thanks you all
I think you mean to persist the hover class when a click occur.
The best option is to use data() to save the state and check on the hover out
var boxes = $('#box_1, #box_2, #box_3, #box_4');
boxes.hover(function() {
$(this).addClass('hover');
}, function() {
if (!$(this).data('clicked'))
$(this).removeClass('hover');
}).click(function(){
boxes.not(this).removeClass('hover').data('clicked',false);;
$(this).data('clicked',true);
});
Is that what you wanted?
http://jsfiddle.net/uhc9S/
CSS: Change your .hover{...}
rule to
#box_1:hover, #box_1.hover,
#box_2:hover, #box_2.hover,
#box_3:hover, #box_3.hover,
#box_4:hover, #box_4.hover {
...
}
JavaScript/jQuery: Don't add the hover class on hover and remove it on unhover. Instead, CSS will handle hover and jQuery just has to handle click:
$('#box_1, #box_2, #box_3, #box_4').click(function() {
$(this).addClass('hover');
});
The :hover
rule means it is hovered. The .hover
rule will be used when you want it to look hovered after it is clicked.
Use mouseover and mouseout
$('#box_1, #box_2, #box_3, #box_4').mouseover(function(){
$(this).addClass('hover');
}).mouseout(function(){
$(this).removeClass('hover');
});
Keep one variable which contains the id of the menuitem clicked
var currentSelected = null;
$('#box_1, #box_2, #box_3, #box_4').click(function(){
currentSelected = this.id;
});
$('#box_1, #box_2, #box_3, #box_4').hover(function(){
if (this.id !== currentSelected){
$(this).addClass("hover");
}
},
function(){
if (this.id !== currentSelected){
$(this).removeClass("hover");
}
});
http://jsfiddle.net/hRnQE/
on click, toggle another 'different' class that does the same thing...
js
$("#box-1, #box-2, #box-3").hover(function() {
$(this).addClass("hover");
}, function() {
$(this).removeClass("hover");
});
$("#box-1, #box-2, #box-3").click(function() {
$(this).toggleClass("hover-clicked");
});
css
.hover {color:red;}
.hover-clicked {color:red;}
精彩评论