首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >显示元素未按预期工作的Javascript mousemove函数

显示元素未按预期工作的Javascript mousemove函数
EN

Stack Overflow用户
提问于 2019-08-06 23:16:13
回答 2查看 105关注 0票数 0

我正在尝试获取一个mousemove函数来显示我在特定div中移动鼠标时创建的自定义光标元素。自定义光标是我希望它出现的div中的一个绝对定位的div。我看到的奇怪的事情是,我可以从开发人员工具中看到它实际上正在工作,但自定义光标并没有真正显示出来。但是,如果我将自定义光标div移到div之外,我希望它进入到主体中,它显示得很好。

我知道这一定是我的一个简单的错误,但我看不出来!感谢您的建议。

代码语言:javascript
复制
let customCursor = document.querySelector('.custom-cursor');
const section2 = document.querySelector('.section2');
section2.addEventListener('mousemove', function(e) {
  customCursor.classList.add('active');
  customCursor.setAttribute("style", "top:" + (e.pageY) + "px; left: " + e.pageX + "px;");

});

section2.addEventListener('mouseleave', function() {
  customCursor.classList.remove('active');
});
代码语言:javascript
复制
.section {
  position: relative;
}

.section1 {
  height: 500px;
}

.section2 {
  height: 500px;
}

.custom-cursor {
  width: 50px;
  height: 50px;
  background: black;
  border-radius: 50%;
  display: none;
  position: absolute;
}

.custom-cursor.active {
  display: block;
}
代码语言:javascript
复制
<body>

  <section class="section1 section">Section 1</section>
  <section class="section2 section">Section 2
    <div class="custom-cursor"></div>
  </section>
</body>

EN

回答 2

Stack Overflow用户

发布于 2019-08-06 23:40:09

就像@Titus注释一样,你可以在cursor中使用CSS。

但是如果你使用JS实现它,需要跟踪鼠标相对于section2的位置,你将需要减去section2元素的左偏移和顶部偏移量,然后减去光标宽度和高度的一半来居中:

代码语言:javascript
复制
let customCursor = document.querySelector('.custom-cursor');
const section2 = document.querySelector('.section2');
section2.addEventListener('mousemove', function(e) {
  customCursor.classList.add('active');
   customCursor.setAttribute("style", "top:" + (e.pageY - section2.offsetTop - (customCursor.offsetWidth/2) ) + "px; left: " + (e.pageX - section2.offsetLeft - (customCursor.offsetHeight/2)) + "px;");

});

section2.addEventListener('mouseleave', function() {
  customCursor.classList.remove('active');
});
代码语言:javascript
复制
.section {
  position: relative;
}

.section1 {
  height: 500px;
}

.section2 {
  height: 500px;
}

.custom-cursor {
  width: 50px;
  height: 50px;
  background: black;
  border-radius: 50%;
  display: none;
  position: absolute;
}

.custom-cursor.active {
  display: block;
}
代码语言:javascript
复制
<body>

  <section class="section1 section">Section 1</section>
  <section class="section2 section">Section 2
    <div class="custom-cursor"></div>
  </section>
</body>

票数 1
EN

Stack Overflow用户

发布于 2019-08-06 23:40:09

代码语言:javascript
复制
position: absolute

是相对于父级的,如果父级具有

代码语言:javascript
复制
position:relative

因此,为了在section2中拥有正确的位置,您需要使用e.layerYe.layerX而不是e.pageYe.pageX,因为它们基于屏幕的左上角。e.layerYe.layerX是相对于鼠标事件所附加到的容器的。

试试这个:https://jsfiddle.net/42kq1w8m/9/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57379178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档