我遇到了一个问题,运行一个循环来触发我的超文本标记语言/样式表的mousemove事件。
我知道我可以通过并获得HTML标记上的每个单独的ID来以我想要的方式执行代码。但我知道有一种更好的方法,那就是使用某种循环,并且使用更少的代码。
当使用mycard类在div上移动时,图像应该跟随鼠标移动。任何关于如何让它正常工作的建议或想法都将非常感谢。
我尝试运行一个循环来将这些类添加到div中,但是没有成功。
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';
};.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;
}<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">×2</p>
</div>
</div>
发布于 2019-06-04 03:18:43
如果我理解您的要求,您可以使用querySelectorAll来获取元素,使用forEach来移动它们:
// 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';
})
});发布于 2019-06-04 03:48:21
我也不完全确定你的最终目标是什么,但我会试一试。
我建议将moveHover改为类而不是ID,然后您可以这样做:
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元素要好。
https://stackoverflow.com/questions/56433226
复制相似问题