簡體   English   中英

如何在圖像 hover 上顯示文本而不是文本 hover - CSS/SASS

[英]How to show text on image hover rather than text hover - CSS/SASS

我確信這是一個簡單的解決方法,但我無法理解我做錯了什么。 我試圖在圖像的 hover 上顯示“標題文本”並降低圖像的不透明度。 我降低了圖像不透明度,但似乎無法使文本出現,除非我直接 hover 文本。 任何幫助,將不勝感激! 謝謝

#work {
  .items {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 1rem;

    .item {
      position: relative;
      background: $dark-color;
      // overflow: hidden;

      &:after {
        content: '';
        position: absolute;
        display: block;
        background: inherit;
        opacity: 0;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
      }

      // bring in main color overlay
      &:hover:after {
        opacity: 0.3;
      }

      &-text {
        position: absolute;
        top: 50%;
        left: 0;
        bottom: 0;
        right: 0;
        opacity: 0;
        text-align: center;
        z-index: 1;
        color: #fff;
      }

      // bring in text on hover
      &-image:hover &-text {
        opacity: 1;
      }

      &-image:before {
        content: '';
        display: block;
        padding-top: 75%;
        overflow: hidden;
      }

      &-image img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: auto;
        line-height: 0;
      }
    }
  }

我認為您可以將圖像和文本包裝在 div 中:

<div class="wrapper">
    <img src="image.jpg">
    <p>Your Title</p>
</div>

<style>
    .wrapper {
        position: relative;
        overflow: hidden;
    }
    .wrapper img {
        display: block;
        max-width: 100%;
        line-height: 0;
    }
    .wrapper p {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        opacity: 0;
        z-index: 2;
    }
    .wrapper:hover img {
        opacity: 0.6;
    }
    .wrapper:hover p {
        opacity: 1;
    }
</style>

如果我對您的理解正確,那么您嘗試做的事情不能僅使用 HTML/CSS 來完成。 您必須使用 JavaScript 才能獲得這樣的效果。

這是一個使用 jQuery 的示例,它將 class.darken 添加到 hover 上的.item。 如果您不重寫代碼,這將不適用於您的情況,但您明白了。 您當然可以在這兩個函數中添加任何內容:

<script>
    (function(){
        jQuery(".item").hover(
            function() {
                jQuery(this).addClass('darken');
            }, function() {
                jQuery(this).removeClass('darken');
            }
        );
    })();
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM