简体   繁体   English

JavaScript显示/隐藏图片

[英]JavaScript showing/hiding pictures

First I will give you my code 首先,我会给你我的代码

<ul>
  <li><a data-img="simon-pics" id="simon" href="#">Simon Cowell</a></li>
  <li><a data-img="bruce-pics" id="bruce" href="#">Bruce Willis</a></li>
  <li><a data-img="ben-pics" id="ben" href="#">Ben Carson</a></li>
</ul>

<img class="hide" id="simon-pics" src="http://upload.wikimedia.org/wikipedia/commons/a/aa/Simon_Cowell_in_December_2011.jpg">
<img class="hide" id="bruce-pics" src="http://upload.wikimedia.org/wikipedia/commons/0/03/Bruce_Willis_by_Gage_Skidmore.jpg">
<img class="hide" id="ben-pics" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Ben_Carson_by_Skidmore_with_lighting_correction.jpg/220px-Ben_Carson_by_Skidmore_with_lighting_correction.jpg" alt="">

That is my HTML code and this is my CSS 那是我的HTML代码,这是我的CSS

.hide {
  display: none;
}

.show {
  display: block
}

So my idea is when I click on the given list element - the corresponding picture to appear - and I succeed with that. 所以我的想法是,当我单击给定的列表元素时-出现相应的图片-然后我成功了。

My problem is that I want when there are more than 2 pictures already opened, my code to automatically closes one of the already opened one's. 我的问题是,当我要打开的图片超过2张时,我的代码自动关闭其中一张已经打开的图片。

var simon = document.getElementById("simon")
var bruce = document.getElementById("bruce")
var ben = document.getElementById("ben")

simon.addEventListener("click", show)
bruce.addEventListener("click", show)
ben.addEventListener("click", show)

function show() {
    let images = document.querySelectorAll("img")
    /* Array.prototype.forEach.call(images, function (x){
        x.className = "hide"
    })*/

    let id = this.attributes["data-img"].value
    let imgId = document.getElementById(id)

    if (imgId.className === "hide") {
        imgId.className = "show"
    } else {
        imgId.className = "hide"
    }

    //till here everything is OK
    let classes = document.querySelectorAll(".show")
    let full = []
    Array.prototype.forEach.call(classes, function (x) {
        full.push(x)
    })

    /*for(let i = 0; i<classes.length; i++){
    full.push(classes[i])

    }*/

    if (full.length > 2) {
        full[1].className = "hide"
        full.shift()
        console.log(full[0].id)
    }
}

And this code works(kind of) - but after a few successful rounds - it stops working - like i am not able to open the third picture and therefore close one of the existing one's 并且此代码有效(有点)-但经过一轮成功的回合后-它停止了工作-就像我无法打开第三张图片,因此关闭了现有图片中的一张

Ok, first of all your show() method works fine on my computer. 好的,首先,您的show()方法在我的计算机上可以正常工作。 The only change that I made is to get the img element and assign the eventListener inside the window.onload function to avoid the risk of get an undefined value. 我所做的唯一更改是获取img元素并在window.onload函数内分配eventListener,以避免获得未定义值的风险。

var simon;
var bruce;
var ben;

window.onload = function(){
simon = document.getElementById("simon")
bruce = document.getElementById("bruce")
ben = document.getElementById("ben")

simon.addEventListener("click", show)
bruce.addEventListener("click", show)
ben.addEventListener("click", show)
}

Here is a simple solution since you already have a data attribute on your elements. 这是一个简单的解决方案,因为您已经在元素上具有数据属性。 This works for es5. 这适用于es5。 You can do some fancier stuff in es6 if you want. 如果需要,可以在es6中做一些更高级的事情。

 var elements = document.getElementsByClassName('imageHideShow'); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('click', show); } function show() { var ele = document.getElementById(this.dataset.img); if (ele.classList.contains('hide')) { var images = imagesShown(); if (images.length === 2) { images[0].classList.remove('show'); images[0].classList.add('hide'); } ele.classList.remove('hide'); ele.classList.add('show'); } else { ele.classList.remove('show'); ele.classList.add('hide'); } } function imagesShown() { var images = document.getElementsByClassName('images'); var returnValue = []; for (var i = 0; i < images.length; i++) { var image = images[i]; if (image.classList.contains('show')) { returnValue.push(image); } } return returnValue; } 
 .hide { display: none; } .show { display: block } 
 <ul> <li><a data-img="simon-pics" class="imageHideShow" href="#">Simon Cowell</a></li> <li><a data-img="bruce-pics" class="imageHideShow" href="#">Bruce Willis</a></li> <li><a data-img="ben-pics" class="imageHideShow" href="#">Ben Carson</a></li> </ul> <img class="hide images" id="simon-pics" src="http://upload.wikimedia.org/wikipedia/commons/a/aa/Simon_Cowell_in_December_2011.jpg"> <img class="hide images" id="bruce-pics" src="http://upload.wikimedia.org/wikipedia/commons/0/03/Bruce_Willis_by_Gage_Skidmore.jpg"> <img class="hide images" id="ben-pics" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Ben_Carson_by_Skidmore_with_lighting_correction.jpg/220px-Ben_Carson_by_Skidmore_with_lighting_correction.jpg" alt=""> 

You can try something like this: 您可以尝试如下操作:

Logic: 逻辑:

  • Create a variable that will hold list of images that are visible. 创建一个变量,将保存可见图像的列表。
  • On click of a , fetch necessary element id from data attribute. 上点击a ,从获取数据属性必需元素的ID。
  • Now check if this exists in current list. 现在检查当前列表中是否存在。 If not, add it to top. 如果没有,请将其添加到顶部。
  • Now check if length is greater than 2 , pop last element and hide this image. 现在检查length是否大于2 ,弹出最后一个元素并隐藏该图像。

Note: I'm using unshift to add and pop to remove. 注意:我正在使用unshift添加和pop以删除。 This is to create a stack like structure. 这是为了创建类似堆栈的结构。 You can altternatively use .push to add and .splice(0,1) to remove as well. 您也可以使用.push进行添加,并使用.splice(0,1)进行删除。

Sample Code 样例代码

 var visibleImages = []; function registerEvents() { var els = document.querySelectorAll('li a'); for (var i = 0; i < els.length; i++) { els[i].addEventListener('click', handleClick); } } function handleClick() { var imgId = this.getAttribute('data-img'); addIDtoList(imgId) showImage(imgId) return false; } function addIDtoList(id) { if (visibleImages.indexOf(id) < 0) visibleImages.unshift(id); if (visibleImages.length > 2) hideImage(visibleImages.pop()) } function showImage(id) { document.getElementById(id).classList.remove('hide'); } function hideImage(id) { document.getElementById(id).classList.add('hide'); } registerEvents(); 
 .hide { display: none; } .show { display: block } img { border: 1px solid black; width: 100px; height: 100px; } 
 <ul> <li><a data-img="simon-pics" id="simon" href="#">Simon Cowell</a></li> <li><a data-img="bruce-pics" id="bruce" href="#">Bruce Willis</a></li> <li><a data-img="ben-pics" id="ben" href="#">Ben Carson</a></li> </ul> <img class="hide" id="simon-pics" src="http://upload.wikimedia.org/wikipedia/commons/a/aa/Simon_Cowell_in_December_2011.jpg"> <img class="hide" id="bruce-pics" src="http://upload.wikimedia.org/wikipedia/commons/0/03/Bruce_Willis_by_Gage_Skidmore.jpg"> <img class="hide" id="ben-pics" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Ben_Carson_by_Skidmore_with_lighting_correction.jpg/220px-Ben_Carson_by_Skidmore_with_lighting_correction.jpg" alt=""> 

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

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