Вопрос

I am using the following code to display an overlay image when the base-image is hovered over:

$(".roll").css("opacity","0"); 
$(".roll").show();
// on mouseover
$(".roll").hover(function () {
  var s = $(this).siblings('img');
  var w = s.css("width");
  var h = s.css("height");

$(this).css("height",h).css("width",w).stop().animate({
   opacity: .6 }, 
   "fast");
 },
// on mouseout
function () {
   $(this).stop().animate({
     opacity: 0
    }, "fast");
 });

This is what the HTML looks like:

 <a class="image"  href="#">
        <span class="roll" style="display:none;"></span>
        <img src="mypic.png" class="image">
 </a>

How do I implement an "on click" event, so that when the image is clicked, the overlay remains instead of disappearing upon mouseout.

I've gotten started with the following, but not sure what else to do:

 $('.roll').on("click", function() {
    if ($(this).hasClass("selected")) {
       $(this).removeClass("selected");
       // remove overlay here?
    }
    else if (!$(this).hasClass("selected")) {
       $(this).addClass("selected");
       // add overlay here?
    }
 });

Probably easy, but I'm not sure how to carry it out beyond the basic mouseover/mouseout.

Thanks!

Это было полезно?

Решение

you can prevent on mouse out function when img has not class selected like

//on mouseout
function () {
    if (!$(this).hasClass("selected"))
    {
       $(this).stop().animate({
        opacity: 0
       });
    }
}

Means you have to check in mouseover/out function that: your images has already clicked or not?

  • Onmouseover:if not already clicked(Selected) then add overlay
  • Onmouseout: if not already clicked(Selected) then remove overlay

Другие советы

Do you want the overlay image to receive the click event, or the base image? I'm going to assume the base image, but the implementation should be basically the same.

// declare a flag in the outer scope
var stickImage = false;
$(".roll").css("opacity", "0");
$(".roll").show();
// on mouseover
$(".roll").hover(function() {
    var s = $(this).siblings('img');
    var w = s.css("width");
    var h = s.css("height");

    $(this).css("height", h).css("width", w).stop().animate({
        opacity: .6
    }, "fast");
});

// on click, toggle the stickImage boolean
$(".roll").click(function() {
    stickImage = !stickImage;
});

// on mouseout
function() {
    // check to make sure stickimage is false before hiding
    if (!stickImage) {
        $(this).stop().animate({
            opacity: 0
        }, "fast");
    }
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top