简体   繁体   English

将父鼠标悬停在上面的图像上

[英]Fill parent div with the image being hovered over

I am still fairly new to JS, and I am trying to replace the HTML of a div with a picture that is being moused over, and when the mouse leaves I want it to return to it's normal state. 我对JS还是很陌生,我试图用鼠标悬停的图片替换div的HTML,当鼠标离开时,我希望它返回到正常状态。 I thought that I did everything right but my code doesn't seem to be working. 我以为我所做的一切都正确,但是我的代码似乎无法正常工作。 I've looked through stack overflow and I see a lot of jQuery solutions to my 'problem,' but I would like an answer in pure JavaScript (I'm trying to "maser" this first), along with an explanation so I can understand why the answer IS the answer. 我已经研究了堆栈溢出问题,并且看到了很多针对我的“问题”的jQuery解决方案,但是我想用纯JavaScript给出答案(我首先尝试“处理”),并附上说明,以便我了解为什么答案就是答案。 Thanks. 谢谢。

I'll try to explain myself (my code). 我将尝试解释一下自己(我的代码)。 I grabbed reference to the image holder, and I grabbed reference to the the images. 我抓取了对图像支架的引用,并且抓取了对图像的引用。 I thought I made a function that looped through the array of images and added an event listener to whichever image ( image[i] ) was being moused over. 我以为我做了一个遍历图像数组的函数,并向鼠标悬停的图像(image [i])添加了一个事件侦听器。 Then, I added an event listener that is supposed to return the image holder to it's default state by inserting the original HTML. 然后,我添加了一个事件侦听器,该侦听器应该通过插入原始HTML来使图像保持器返回其默认状态。 I just don't understand how to fix this. 我只是不知道如何解决此问题。

var holder = document.getElementById('holder');
var images = document.getElementsByTagName('img');

var popImage = function () {
    for (i = 0; i < images.length; i++) {
        images[i].addEventListener('mouseover', = function () {
            holder.innerHTML = images[i];
        });
        images[i].addEventListener('mouseout', function () {
            holder.innerHTML = 
                '<div class='col-md-3 img-fluid' id='img1'><img src='photo1.jpg'></div>
                <div class='col-md-3 img-fluid' id='img2'><img src='photo2.jpg'></div>
                <div class='col-md-3 img-fluid' id='img3'><img src='photo3.2.jpg'></div>
                <div class='col-md-3 img-fluid' id='img4'><img src='photo4.jpg'></div>'
        });
    };
};

popImage();

You said you are new to JS and just learning which is great but an important part of learning JS is learning when not to use it. 您说过,您是JS的新手,只是学习是很棒的,但是学习JS的重要部分是学习何时使用它。 As @Yoda said if this was for production you really should use CSS instead of JS. 正如@Yoda所说,如果这是用于生产,那么您确实应该使用CSS而不是JS。

Here is one way you could accomplish this with pure CSS 这是使用纯CSS完成此操作的一种方法

 <style> .img { width: 100px; height: 100px; background: #bada55; border: 2px solid #333; float: left; } .holder:hover > .img { opacity: 0; } .holder:hover > .img:hover { opacity: 1; } </style> <div class="holder"> <!-- Using div.img for simplicity, these whould be your <img/> tags --> <div class="img">1</div> <div class="img">2</div> <div class="img">3</div> <div class="img">4</div> </div> 

For the purpose of learning, here's how you'd do it in JS: 为了学习的目的,这是您在JS中要做的事情:

 var holder = document.getElementById('holder'); var images = document.querySelectorAll('.img'); var filter = false; function popImage () { // Use for (var i = 0 . . . // Instead of for (i = 0 . . . // Because without var, i will be stored in the global scope for (var i = 0; i < images.length; i++) { (function (_i) { images[_i].addEventListener('mouseover', function () { holder.innerHTML = ''; // We can't set innerHTML to images[_i] // because it's a DomNode not a string holder.appendChild(images[_i]); }); })(i); } holder.addEventListener('mouseout', function (e) { if (e.target !== holder) return; holder.innerHTML = ''; // Again, use var j = 0 . . . for (var j = 0; j < images.length; j++) { holder.appendChild(images[j]); } }); } popImage(); 
 .img { width: 100px; height: 100px; background: #bada55; border: 2px solid #333; display: inline-block; } #holder { position: relative; width: 100%;// So doesn't collape and trigger mouseout height: 100px; background: red; padding: 20px 0; } 
 <div id="holder"> <!-- Again, these would be your image tags --> <div class="img">1</div> <div class="img">2</div> <div class="img">3</div> <div class="img">4</div> </div> 

I had 10 mins before leaving work so I had a crack at this to see how I would do it and give you some ideas. 我下班前有10分钟的时间,所以我很想了解如何做并给您一些想法。

Here is my implementation ( https://jsfiddle.net/hg7s1pyh/ ) 这是我的实现( https://jsfiddle.net/hg7s1pyh/

I guess the main thing here is that I've broken it down into lots of smaller parts, this makes solving problems far easier, each method is concerned with doing one thing only. 我想这里的主要问题是我将其分解为许多较小的部分,这使解决问题变得容易得多,每种方法只关心做一件事情。

You will also note the use of classes to show and hide content rather than removing it entirely, this takes lots of the arduous work out of this feature. 您还将注意到使用类来显示和隐藏内容,而不是将其完全删除,这使该功能花费了很多艰巨的工作。

 function attachEvents() { var images = getImages(); images.forEach(function(image) { attachMouseOverEvent(image); attachMouseLeaveEvent(image); }); } function attachMouseOverEvent(element) { element.addEventListener('mouseover', function(e) { var clonedImage = e.target.cloneNode(); addImageToPreview(clonedImage); }); } function attachMouseLeaveEvent(element) { element.addEventListener('mouseleave', function(e) { removeImageFromPreview(); }); } function getImages() { return document.querySelectorAll('.js-image'); } function getImagePreviewElement() { return document.querySelector('.js-image-box'); } function addImageToPreview(imageElement) { var previewElement = getImagePreviewElement(); previewElement.classList.add('previewing'); previewElement.appendChild(imageElement); } function removeImageFromPreview() { var previewElement = getImagePreviewElement(); previewElement.classList.remove('previewing'); var image = previewElement.querySelector('.js-image'); image.remove(); } attachEvents(); 
 .image-box { position: relative; min-height: 400px; width: 400px; border: 1px solid #000; text-align: center; } .image-box .placeholder { position: absolute; top: 50%; text-align: center; transform: translateY(-50%); width: 100%; } .image-box.previewing .placeholder { display: none; } .image-box .image { position: absolute; top: 50%; text-align: center; transform: translate(-50%, -50%); height: 100%; width: 100%; } .images { margin-top: 10px; } 
 <div class="js-image-box image-box"> <div class="placeholder"> Placeholder </div> </div> <div class="images"> <div class="col-md-3 img-fluid"><img class="js-image image" src="http://placehold.it/350x150"></div> <div class="col-md-3 img-fluid"><img class="js-image image" src="http://placehold.it/150x150"></div> <div class="col-md-3 img-fluid"><img class="js-image image" src="http://placehold.it/400x400"></div> <div class="col-md-3 img-fluid"><img class="js-image image" src="http://placehold.it/350x150"></div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM