如何根据热点悬停设置不同的背景



如何修改此代码笔https://codepen.io/varcharles/pen/qNQpRv当鼠标悬停在红点上时,右侧的框应该更改为与所选热点的背景相关。因此,四张不同的图像与四个不同的热点有关。

const dataField = document.querySelector('.data');
const points = [
{
x: '30px',
y: '50px',
data: 'Targeting Lasers',

},
{
x: '460px',
y: '210px',
data: 'Targeting Lasers'
},
{
x: '250px',
y: '350px',
data: 'Sheild Generators'
},
{
x: '3890px',
y: '550px',
data: 'Sensor Array'
}
];
points.forEach((point) => {
let img = document.createElement('img'); 
img.style.left = point.x;
img.style.top = point.y;
img.title = point.data;
img.className= 'overlay-image';
img.src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/544303/Target_Logo.svg"
overlay.appendChild(img);
img.data = point.data;
img.addEventListener('mouseenter', handleMouseEnter);
img.addEventListener('mouseleave', handleMouseLeave);
});
function handleMouseEnter(event) {
dataField.innerHTML = event.currentTarget.data;
}

function handleMouseLeave(event) {
dataField.innerHTML = ' ';
}

有人能帮帮我吗?非常感谢您的关注

您只需添加更多数据并将每个数据对象分配给图像即可。以下内容将更改悬停在热点上时的背景图像。

const overlay = document.querySelector('.image-overlay');
const dataField = document.querySelector('.data');
const points = [
{
x: '320px',
y: '50px',
data: {
title: 'Extended Cockpit',
image: "url('https://dummyimage.com/320x320/ff0000/fff')",
}
},
{
x: '460px',
y: '210px',
data: {
title: 'Targeting Lasers',
image: "url('https://dummyimage.com/320x320/00ff00/fff')",
}
},
{
x: '250px',
y: '350px',
data: {
title: 'Sheild Generators',
image: "url('https://dummyimage.com/320x320/0000ff/fff')",
}  
},
{
x: '3890px',
y: '550px',
data: {
title: 'Sensor Array',
image: "url('https://dummyimage.com/320x320/000000/fff')",
}
}
];
points.forEach((point) => {
let img = document.createElement('img'); 
img.style.left = point.x;
img.style.top = point.y;
img.title = point.data.title;
img.className= 'overlay-image';
img.src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/544303/Target_Logo.svg"
overlay.appendChild(img);
// Sets title and image data attributes
img.data = point.data;
img.addEventListener('mouseenter', handleMouseEnter);
img.addEventListener('mouseleave', handleMouseLeave);
});
function handleMouseEnter(event) {
// Set title and background image based on data set in target
dataField.innerHTML = event.currentTarget.data.title;
dataField.style.backgroundImage = event.currentTarget.data.image;
}
function handleMouseLeave(event) {
// Reset
dataField.innerHTML = ' ';
dataField.style.backgroundImage = 'none';
}

最新更新