【问题标题】:Fade a background image down on hover to reveal the background color?在悬停时淡化背景图像以显示背景颜色?
【发布时间】:2015-08-27 20:27:06
【问题描述】:

是否可以在悬停时淡化背景图像的不透明度以显示更多的背景颜色?

本质上,我希望背景颜色为黑色,因此当图像悬停时,它看起来会变暗。

这是它的设置方式:

<a href="#" class="new-cinema" style="background-image:url('images/promo-1.jpg');">
    <span class="main-title">New<br />Cinema<br />Openings</span>
</a>

通过使用类似下面的东西,它只是淡化了图像:

opacity: 0.75;
transition: opacity .25s ease-in-out;
-moz-transition: opacity .25s ease-in-out;
-webkit-transition: opacity .25s ease-in-out;

【问题讨论】:

  • 您是否尝试过任何 jQuery 来完成这项工作?

标签: jquery css


【解决方案1】:

您可以通过将物理图像添加到 DOM 并降低悬停时图像的不透明度来实现。您不需要 jQuery,但这里有一个纯 CSS 解决方案:

a {position: relative; overflow: hidden; background: #000; display: inline-block;}
a img {position: absolute; left: 0; top: 0;}
a img, a:hover img {transition: opacity .25s ease-in-out; -moz-transition: opacity .25s ease-in-out; -webkit-transition: opacity .25s ease-in-out;}
a:hover img {opacity: 0.5;}
<a href="#" class="new-cinema">
  <img src="http://lorempixel.com/400/200/" />
  <span class="main-title">New<br />Cinema<br />Openings</span>
</a>

【讨论】:

    【解决方案2】:

    您可以使用伪元素来做到这一点,并将样式保留在 CSS 中,而不是在 HTML 中保留图像。

    .new-cinema {
      display: inline-block;
      margin: 25px;
      border: 1px solid green;
      text-align: center;
      background: black;
      font-weight: bold;
      color: red;
      padding: .5em;
      position: relative;
      text-decoration: none;
    }
    .new-cinema:after {
      content: '';
      position: absolute;
      background: #000;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      background-image: url(http://lorempixel.com/200/200/sports/);
      background: cover;
      transition: opacity 0.5s ease;
    }
    .new-cinema:hover:after {
      opacity: 0.5;
    }
    .main-title {
      position: relative;
      z-index: 1;
    }
    <a href="#" class="new-cinema">
      <span class="main-title">New<br />Cinema<br />Openings</span>
    </a>

    【讨论】:

      【解决方案3】:

      尝试使用插入 box-shadow。如果这是性能问题,请纠正我。

      a {
        box-shadow: inset 0px 0px 0px 100px rgba(255, 255, 255, 0);
        transition: box-shadow .25s ease-in-out;
      }
         a:hover {
           box-shadow: inset 0px 0px 0px 100px rgba(0, 0, 0, 0.8);
         }
      

      Jsfiddle:https://jsfiddle.net/q5osfcg2/

      【讨论】:

        猜你喜欢
        • 2017-06-28
        • 2014-07-24
        • 2011-10-23
        • 2019-06-23
        • 1970-01-01
        • 2013-01-27
        • 1970-01-01
        • 2013-10-23
        相关资源
        最近更新 更多