创建圆形鼠标悬停饱和效果

2024-03-04

我有两个版本的图像:去饱和版本和全彩版本。我想要实现的是悬停效果,其中将鼠标悬停在去饱和图像上会显示图像的彩色版本的圆圈。这有点像将聚光灯照射在饱和度降低的图像上以显示其颜色。然后,当您将鼠标移开时,它会淡回到不饱和状态。

我知道我可能可以使用 flash,但我想使用 JavaScript 和 CSS 来完成此操作。理想情况下,如果 JavaScript 被禁用并且宽度可以流动(响应式),这将降级为仅图像。


边界半径

CSS3 border-radius可用于创建带有背景图像的圆形 div,用作图像聚光灯。聚光灯可以覆盖在主图像的顶部,并根据鼠标坐标进行定位。JSFiddle 演示 http://jsfiddle.net/CkJXJ/3/

尽管 CSS3 中没有自然的方法来柔化聚光灯的边缘(这需要支持向任意内容添加不透明度渐变),但可以使用一组交错的元素进行模拟,这些元素的半径不断增加,不透明度不断减小。更新了演示,边缘柔化了 http://jsfiddle.net/ga2D2/3/

In the 更新了演示 http://jsfiddle.net/ga2D2/3/,聚光灯的大小和柔和度可以使用以下变量进行调整:

var spotlightDiameter = 150;      // Base size (not including the soft edge)
var numSpotlightLayers = 6;       // More layers = softer edges
var spotlightLayerThickness = 2;  // Thinner = the softening is more subtle

这是一个修改演示 http://jsfiddle.net/bu7rd/聚光灯有明显波纹的地方。增加了层的厚度以更清楚地显示其工作原理。

下面是带有锐边的初始版本的代码的简化版本。

HTML

<div class="content">
    <div class="spotlight"></div>
</div>

CSS

.content {
    position: relative;
    width: 640px;
    height: 480px;
    background: url(desaturated.jpg) no-repeat 0 0;
    overflow: hidden;
}
.spotlight {
    display: none;
    position: absolute;
    background: url(overly_saturated.jpg) no-repeat 0 0;
}

jQuery

var spotlightDiameter = 150;

// Update the spotlight position on mousemove
$('.content').on('mousemove', function(e){
    var center = {x: e.pageX - this.offsetLeft,
                  y: e.pageY - this.offsetTop};
    var x = center.x - (spotlightDiameter >> 1);
    var y = center.y - (spotlightDiameter >> 1);

    $('.spotlight').css({left: x + 'px', top: y + 'px',
                         backgroundPosition: -x + 'px ' + -y + 'px'}).show();
});

// Hide the spotlight on mouseout
$('.content').on('mouseout', function(e){
    $('.spotlight').hide();
});

// Initialize the spotlight
$(document).ready(function(){
    $('.spotlight').width(spotlightDiameter + 'px')
                   .height(spotlightDiameter + 'px')
                   .css({borderRadius: (spotlightDiameter >> 1) + 'px'});
});

替代实现

这也可以使用 HTML5 Canvas 或 SVG 来实现。以下是不同方法的浏览器支持比较:

  • border-radius: 不支持IE8或更早版本 http://caniuse.com/#search=border-radius.
  • HTML5 Canvas:不支持IE8或更早版本 http://caniuse.com/#search=canvas.
  • SVG:不支持IE8或更早版本 http://caniuse.com/#search=svg, or Android 2.3 或更早版本 http://caniuse.com/#search=svg(这仍然是大多数安卓市场份额 http://developer.android.com/about/dashboards/index.html).

简而言之,IE8 及更早版本都不适用于任何这些方法,如果需要 Android 支持,则选择范围会受到限制border-radius和 HTML5 画布。当然,由于这是基于鼠标的,Android 支持无论如何可能不是一个因素。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

创建圆形鼠标悬停饱和效果 的相关文章

随机推荐