0

I have to place three images side by side, and onmouseover function, when the user moves the mouse over an image , that particular image will be duplicate on the other two images. When the use moves the mouse out from the image, the image will restore as in initial page. But I have to use childnodes for this. I'm not able to figure this out.

I've tried this following code, but it doesn't do anything. I tried to paste the code here, but it was getting out onto the body of the message so I made this codepen where you can see it. So far I'm only to get index[1] and index[2] pic to show up on index[0], but no other changes are happening. https://codepen.io/anon/pen/xNjezN

function heroes(q){
    if(q.src == imgArray[0])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[0];
        }
    }
    else if(q.src == imgArray[1])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[1];
        }
    }
    else if(q.src == imgArray[2])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[2];
        }
    }
}

If someone can please suggest something.

4

2 回答 2

1

如果这是您想要的,我刚刚选择img了您想要从onmouseout事件中获取 src 的所有标签。onmouseout回调函数我刚刚将mnImg.src值替换为当前图像 src。

如果你想在鼠标悬停时替换 img src,你可以onmouseoutonmouseover.

鼠标移出

let images = document.querySelectorAll('.img');
let mnImg = document.querySelector('#mnImg');

images.forEach(img => {
  img.onmouseout = function() {
    mnImg.src = this.src;
  };
})
img {
  height: 100px;
  width: 100px;
}
<body>
  <div id="legends">
    <img src="https://imagizer.imageshack.com/img921/9646/HCBvlG.jpg" id="mnImg">
    <img src="https://imagizer.imageshack.com/img924/3295/Fb6gMO.jpg" class='img'>
    <img src="https://imagizer.imageshack.com/img923/6089/01GQK7.jpg" class='img'>
  </div>
</body>

鼠标悬停

let images = document.querySelectorAll('.img');
let mnImg = document.querySelector('#mnImg');

images.forEach(img => {
  img.onmouseover = function() {
    mnImg.src = this.src;
  };
})
img {
  height: 100px;
  width: 100px;
}
<body>
  <div id="legends">
    <img src="https://imagizer.imageshack.com/img921/9646/HCBvlG.jpg" id="mnImg">
    <img src="https://imagizer.imageshack.com/img924/3295/Fb6gMO.jpg" class='img'>
    <img src="https://imagizer.imageshack.com/img923/6089/01GQK7.jpg" class='img'>
  </div>
</body>

于 2019-05-26T19:33:37.303 回答
0

您快到了。有两点需要注意。一,子节点实际上是一个“NodeList”,它只是“类数组”。可以使用 Array.from(nodeList) 将其转换为数组。其次是换行符被读取为“文本”节点,因此实际上显示了 7 个子节点。Array.prototype.filter()您可以使用方法将它们过滤掉。

子节点

然后,一旦您使用实际的 DOM 元素,就可以设置和重置 src:https ://codepen.io/anon/pen/vwjwXm?editors=1010

于 2019-05-26T20:14:28.397 回答