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

问题描述 投票:0回答:1

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

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 = ' ';
}

有人可以帮助我吗?非常感谢您的关注

javascript html css
1个回答
1
投票

您可以添加更多数据并将每个数据对象分配给图像。下面将改变悬停热点时的背景图片。

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';
}
© www.soinside.com 2019 - 2024. All rights reserved.