边界半径
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 支持无论如何可能不是一个因素。