我正在尝试使用javascript在图像上创建聚光灯幻觉。
我在jsfiddle中使其完美工作(请参阅:http://jsfiddle.net/5erkpq8c/),但是当我将其添加到我的网站时,我得到的聚光灯效果偏离了鼠标指针,或者是左上角的静态聚光灯在图像的一角看到https://visiondigital.marketing/test-page/处的错误示例。
我遇到的另一个问题是,如果聚光灯随指针移动(但发生偏移),则偏移量会根据屏幕大小而变化。
var spotlightDiameter = 150;
var numSpotlightLayers = 6;
var spotlightLayerThickness = 2;
// Verify that the mouse event wasn't triggered by a descendant.
function verifyMouseEvent(e, elem) {
e = e || window.event;
var related = e.relatedTarget || e.toElement;
while ((related != undefined) &&
(related != elem) &&
(related.nodeName != 'BODY'))
{
related = related.parentNode;
}
return (related != elem);
}
// Create the spotlight
function createSpotlight() {
$('.spotlight').width(spotlightDiameter + 'px')
.height(spotlightDiameter + 'px');
for (var i = 0; i < numSpotlightLayers; i++) {
var layerDiameter = spotlightDiameter + (i * spotlightLayerThickness * 2);
var opacity = 1 - (i / numSpotlightLayers);
$('.spotlight').append('<div class="layer' + i + '"></div>');
$('.spotlight .layer' + i)
.width(layerDiameter + 'px')
.height(layerDiameter + 'px')
.css({borderRadius: (layerDiameter >> 1) + 'px',
opacity: opacity,
zIndex: (numSpotlightLayers - i)});
}
}
// Mousemove
$('.contenthome1').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);
for (var i = 0; i < numSpotlightLayers; i++) {
var offset = i * spotlightLayerThickness;
$('.spotlight .layer' + i)
.css({left: -offset + 'px',
top: -offset + 'px',
backgroundPosition: -(x - offset) + 'px ' + -(y - offset) + 'px'})
}
$('.spotlight').css({left: x + 'px', top: y + 'px'}).show();;
});
// Mouseout
$('.contenthome1').on('mouseout', function(e){
if (!verifyMouseEvent(e, this)) return;
$('.spotlight').hide();
});
$(document).ready(function(){
createSpotlight();
});
我真的希望聚光灯坐下,以便无论屏幕大小如何,鼠标指针都位于聚光灯的中心。