首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >onmousemove事件的循环

onmousemove事件的循环
EN

Stack Overflow用户
提问于 2019-06-04 03:08:29
回答 2查看 317关注 0票数 0

我遇到了一个问题,运行一个循环来触发我的超文本标记语言/样式表的mousemove事件。

我知道我可以通过并获得HTML标记上的每个单独的ID来以我想要的方式执行代码。但我知道有一种更好的方法,那就是使用某种循环,并且使用更少的代码。

当使用mycard类在div上移动时,图像应该跟随鼠标移动。任何关于如何让它正常工作的建议或想法都将非常感谢。

我尝试运行一个循环来将这些类添加到div中,但是没有成功。

代码语言:javascript
复制
var mouseHover = document.getElementById('moveHover');

window.onmousemove = function(e) {

  var x = e.clientX;
  var y = e.clientY;
  mouseHover.style.top = (y + 20) + 'px';
  mouseHover.style.left = (x + 20) + 'px';
};
代码语言:javascript
复制
.mycard span {
  position: absolute;
  display: none;
  z-index: 99;
}

.mycard:hover span {
  display: block;
  position: fixed;
  overflow: hidden;
}

.imgHover a {
  position: relative;
}

.imgHover span {
  position: absolute;
  display: none;
  z-index: 99;
}

.imgHover a:hover span {
  display: block;
  position: fixed;
  overflow: hidden;
}
代码语言:javascript
复制
<div class="imgHover mycard">
  <div class="cardcost">
    <p class="cardcosttext">2</p>
  </div>
  <div class="hscardepic">
    <a style="margin-left: 1000%;vertical-align: middle;">
      Doomsayer
      <span id="moveHover">
        <img src="Classic_Set/doomsayer.png" height="300" width="300" /> 
      </span>
    </a>
  </div>
  <div class="cardamount">
    <p class="cardamounttext">&times;2</p>
  </div>
</div>

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-06-04 03:18:43

如果我理解您的要求,您可以使用querySelectorAll来获取元素,使用forEach来移动它们:

代码语言:javascript
复制
// get the div that responds to mouse movement
const mycard = document.querySelector('.mycard');

// add a mousemove listener
mycard.addEventListener('mousemove', function(e) {
  // get the DOM element with the mousemove listener from the event
  const {target} = e;

  // get img child elements of the target.
  // (use whatever css selector you need here. doesn't have to img)
  const images = target.querySelectorAll('img');

  // iterate over each item...
  images.forEach(image => {
    // ...and do whatever you need to do with it
    const x = e.clientX;
    const y = e.clientY;
    image.style.top = (y + 20) + 'px';
    image.style.left = (x + 20) + 'px';
  })
});
票数 0
EN

Stack Overflow用户

发布于 2019-06-04 03:48:21

我也不完全确定你的最终目标是什么,但我会试一试。

我建议将moveHover改为类而不是ID,然后您可以这样做:

代码语言:javascript
复制
var mouseHover = null;

window.onmousemove = function (e) {
  if(mouseHover != null){
    var x = e.clientX;
    var y = e.clientY;
    mouseHover.style.top = (y+20) + 'px';
    mouseHover.style.left = (x+20) + 'px';
  }
};

function onHover(e){
  mouseHover = e.target.querySelector('.moveHover');
}

var elements = document.getElementsByClassName('imgHover');
for(var i = 0; i < elements.length; i++){
  elements[i].onmouseenter = onHover;
}

循环运行一次以设置onmouseenter事件。当然也比一直移动所有.moveHover元素要好。

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

https://stackoverflow.com/questions/56433226

复制
相关文章

相似问题

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