我们如何使用JavaScript DOM更改背景图像的线性渐变?

问题描述 投票:0回答:1
document.querySelector('.image').addEventListener('mousemove',(e)=>{

    document.querySelector('.image').style.backgroundImage = 'linear-gradient(to top,rgba(${e.offsetX},${e.offsetY},22,0.5),rgba(31, 22, 26, 0.8)), url("https://pics.freeartbackgrounds.com/fullhd/Morning_Sea_and_Boat_Background-318.jpg")';

});

我编写了此EventListener函数,并希望通过mousemove事件更改背景图像的渐变。这不起作用。

javascript html css dom linear-gradients
1个回答
0
投票

我相信您错过了``就这样

window.onload = ()=> {
  document.querySelector('.image').addEventListener('mousemove',(e)=>{
    const style = `linear-gradient(to top right,rgba(${e.offsetX},${e.offsetY},22,0.5),rgba(31, 22, 26, 0.8))`;
    console.log(style);
    document.querySelector('.image').style.backgroundImage = style;
  });
}
<html>
  <head></head>
  <body>
    <image  width="200" height="200" class="image" src="" />
  </body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.