javascript 自定义光标悬停在图像上时返回默认值

6qfn3psc  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(110)

我在一个网站上工作,我实现自定义光标。这些光标根据背景而变化,但是,当光标靠近/位于地球图像的顶部时,光标返回默认值。下面是我的HTML代码:

<div class="main-wrapper">
            <div class="season winter" data-background="#2b1055">Winter</div>
            <div class="season summer" data-background="#5988e2">Summer</div>
            <div class="season spring" data-background="#7cdea1">Spring</div>
            <div class="season autumn" data-background="#cf8a8a">Autumn</div>
        </div>

        <div class="wrapper">
            <div>
                <img id="earth" src="img/earth.png" alt="scroll">
            </div>
        </div>

CSS:

body {
  transition: background 1s ease-in-out;
}

.season {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  color: #fff;
  font-family: sans-serif;
  font-size: 72px;
  font-weight: 600;
  text-transform: uppercase;
  &[data-background="yellow"] { color: #333; };
}

.winter {
  cursor: url('img/winter-cursor.png'), auto;
}

.summer {
  cursor: url('img/summer-cursor.png'), auto;
}

.spring {
  cursor: url('img/spring-cursor.png'), auto;
}

.autumn {
  cursor: url('img/autumn-cursor.png'), auto;
}

.wrapper {
  top: 120%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
}

#earth {
  width: 800px;
  height: 800px;
}

JavaScript(用于滚动时地球的旋转和背景的变化):

// Rotating earth 
window.onscroll = function() {
  scrollRotate();
};

function scrollRotate() {
  let image = document.getElementById("earth");
  image.style.transform = "rotate(" + window.pageYOffset / 24 + "deg)";
}

// Background change 
window.sections = [...document.querySelectorAll('.season')];
window.lastScrollTop = window.pageYOffset;

document.body.style.background = window.sections[0].getAttribute('data-background');

window.addEventListener('scroll', onScroll);

function onScroll() {
  const scrollTop = window.pageYOffset;
  const section = window.sections
    .map(section => {
      const el = section;
      const rect = el.getBoundingClientRect();
      return {el, rect};
    })
    .find(section => section.rect.bottom >= (window.innerHeight * 0.5));

  document.body.style.transition = 'background 1s cubic-bezier(0.3, 0.3, 0.3, 0.3)';
  document.body.style.background = section.el.getAttribute('data-background');

}

为了解决这个问题,我尝试通过向下移动地球图像来重新排列html文件中元素的位置,但似乎没有任何效果。
我也试着在CSS文件中将#earth的光标更改为none,但这只会使光标完全消失:(
任何回应都很感激,谢谢!

s8vozzvw

s8vozzvw1#

希望下面的答案适合你。

window.onscroll = function() {
  
  var getCurrentClassName =//add some code for getting class name based on scroll;
  scrollRotate(getCurrentClassName);//"winter"
  
};

function scrollRotate(seasonName) {
  let image = document.getElementById("earth");
  image.classList.replace(seasonName);
  image.style.transform = "rotate(" + window.pageYOffset / 24 + "deg)";
}

相关问题