简体   繁体   中英

How can I get only the specific H3 I am hovering over to show and not all of them?

I am trying to have text appear over each image as the user hovers over that specific image. I don't want all of the text for every image to appear when a user hovers over one image. I have it where only the one photo becomes opaque but right now the text shows up for every image when hovering over any image.

HTML:

<div class="image">
  <img class="projectImage" src="images/peralta.png" alt="">
  <h3 class="hiddenH3">This is a test!</h3>
</div>

SCSS:

.image {
  position: relative;
  width: 100%;
  .projectImage {
    width: 100%;
    transition: all 0.5s ease-in;
  }
  .hiddenH3 {
    display: none;
    position: absolute;
    top: 45%;
    width: 100%;
  }
}

JS:

$('.projectImage').on("mouseover", function() {
  $(this).closest('.projectImage').addClass("coolEffect");
  $('.hiddenH3').fadeIn(1000);
  });
$('.projectImage').on("mouseout", function() {
  $(this).closest('.projectImage').removeClass("coolEffect");
  $('.hiddenH3').fadeOut(1000);
  });

Use .next along with this

$('.projectImage').on("mouseover", function() {
    $(this).addClass("coolEffect");
    $(this).next(".hiddenH3").fadeIn(1000);
});
$('.projectImage').on("mouseout", function() {
    $(this).removeClass("coolEffect");
    $(this).next(".hiddenH3").fadeOut(1000);
});

You can also remove .closest(".projectImage") as this refers to that image.

Why don't you do this with CSS? Since the selectors needed are very old and entrenched, you can do something like this:

.projectImage + h3 {
    transition: opacity 1000ms;
    opacity: 0;
}
.projectImage:hover + h3 {
    opacity: 1;
}

This will fade in your h3 when you hover over the project image, as long as you structure it in that way (ie, ing, then h3). You can also remove the classes cooLEffect and hiddenh3 as we have defined that by only targeting the h3 that comes after a project image.

The fancy transition effect will only work on modern browser, but older browsers gracefully degrade.

Edit: SASS / LESS

.image {
    .projectImage {
        & + h3 {
            transition: opacity 1000ms;
            opacity: 0;
        }
        &:hover + h3 {
            opacity: 1;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM