Conditional change (if/then) based on css property in jquery
I have several images:
<img class="photo" src="{{ img.url_small }} />
<img class="photo" src="{{ img.url_small }} />
<img class="photo" src="{{ img.url_small }} />
I'm trying to change the border color when the user hovers over the image or clicks on it:
$(".photo").click(function() {
$(".photo").css({"background":"white"});
$(this).css({"background":"blue"});
});
$(".photo").mouseenter(function() {
$(this).css({"background":"green"});
}).mouseleave(function() {
$(this).css({"background":"white"});
});
(there is a white margin around each image thus that a change in background changes the border)
The trouble is when a user clicks on an image, it turns blue, but then when the mouse is moved from the image, the border turns white.
I tried some conditionals:
$(".photo").mouseenter(function() {
if($(this).css("background") != "blue") {
$(this).css({"background":"green"});
}
}).mouseleave(function()开发者_如何学编程 {
if($(this).css("background") != "blue") {
$(this).css({"background":"white"});
}
});
but the borders still turned back white from blue. How can I keep the border blue? Is there a more efficient way of doing this?
Don't use javascript for what you can do in CSS.
CSS will take care of the simple hover
style change, then just add a class for the click
.
If you need to support IE6 for the hover, I'd wrap the <img>
in a <a>
tag, and give that the background.
Live Example: http://jsbin.com/ogasa3
.photo {
background:white;
}
.photo:hover {
background:green;
}
.selected {
background:blue;
}
.selected:hover {
background:blue;
}
jQuery
$(".photo").click(function() {
$(".photo.selected").removeClass('selected');
$(this).addClass('selected');
});
.hover is the more efficient way of doing mouseenter, mouseleave.
What you really need to do is when an image is clicked add a new class to it, like so:
$(".photo").click(function() {
$(".photo").removeClass('currentImage');
$(this).addClass('currentImage');
});
$(".photo").hover(function() {
jQuery(this).addClass('hoverImage');
}, function() {
jQuery(this).removeClass('hoverImage');
});
make sure that currentImage is styled like you want:
.currentImage {
background:blue;
}
.hoverImage {
background:green;
}
精彩评论