【问题标题】:Fading between sprite images without calling out image url in CSS在精灵图像之间淡入淡出而不在 CSS 中调用图像 url
【发布时间】:2018-02-16 16:41:05
【问题描述】:

是否可以在悬停时在精灵图像之间淡出而不在 CSS 中调用图像 URL?

我有大量的两张图片精灵表。我希望每个人都打开悬停,但是如果我必须为每个人创建一个具有“背景:url(x)”的新元素,那么 CSS 将过于臃肿。

.frame {
  height: 500px;
  width: 500px;
  overflow: hidden;
}

.sprite {
  background: url(image.png) 0px 0px no-repeat;
  position: relative;
  height: 500px;
  width: 500px;
}

.sprite::after {
  content: "";
  background: url(image.png) -500px 0px no-repeat;
  opacity: 0;
  transition: opacity 0.35s;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.sprite:hover::after {
  opacity: 1;
  transition: opacity: 0.35s;
}

我宁愿在这里叫他们:

<div class="sprite frame">
    </div>

Here's a JSFiddle of the effect I want,但我想在 HTML 中调出图片 URL,所以我没有 100 个不同的 CSS 元素调出不同的图片。

【问题讨论】:

    标签: html css hover css-transitions sprite


    【解决方案1】:

    嗯。如果您对 jQuery 解决方案持开放态度,这可能会有所帮助。您可以使用“data alt-src”HTML 属性在一个标签中存储两个图像 URL,然后在该类上调用 jQuery .hover() 函数。

    HTML:

    <img class="xyz" data-alt src="http://cdn1.iconfinder.com/data/icons/fatcow/32/accept.png" src="http://cdn1.iconfinder.com/data/icons/fatcow/32/cancel.png" />
    

    jQuery:

        var sourceSwap = function () {
        var $this = $(this);
        var newSource = $this.data('alt-src');
        $this.data('alt-src', $this.attr('src'));
        $this.attr('src', newSource);
    }
    
    $(function () {
        $('img.xyz').hover(sourceSwap, sourceSwap);
    });
    

    http://jsfiddle.net/LmVRZ/2/

    我意识到这个演示不包括不透明度过渡,但我认为它可以内置。

    【讨论】:

    • 我通过使用“object-position”实现了与没有 jQuery 的类似解决方案,但我不确定不透明度转换是否适用于此,因为它基本上只是将 spritesheet 移动过来。如果可能的话,我想只用 CSS/HTML 来做。如果没有,我将不得不想出别的办法。不过我很感激你。你的回答对我很有价值。
    猜你喜欢
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    相关资源
    最近更新 更多