简体   繁体   English

如何通过单击同一父div内的图片标签来定位隐藏的div? Vanilla JS事件监听器

[英]How to target a hidden div by clicking on an image tag that is within the same parent div? Vanilla JS Event Listeners

I got this code. 我得到了这段代码。

Express-Handlebars: 快速车把:

{{#each bigProjectList}}
    <div class="bigProjIndividual">

        <img src="{{image}}" alt="">

        <div class="bigProjDesc">

            <h5>{{name}}</h5>
            <p>{{tech}}</p>
            <p>{{desc}}</p>

            {{#if web.gitHub}}
            <a href="{{web.github}}"target="_blank"> <img src="/github.png" alt="github"> </a>
            {{/if}}

            {{#if web.website}}
            <a href="{{web.website}}"target="_blank"> <img src="/website.png" alt="github"> </a>
            {{/if}}

        </div>
    </div>
{{/each}}

It is fetching the data from a json file I have in the directory. 它正在从目录中的json文件中获取数据。

I would like the class 'bigProjDesc' to be initially hidden and then shown once the user click on the <img> tag. 我希望类'bigProjDesc'最初被隐藏,然后在用户单击<img>标记后显示。

I am currently using vanilla JS / CSS / Express-Handlebars. 我目前正在使用香草JS / CSS / Express-Handlebars。

It's done pretty easy: 这很容易做到:

 const imgList = document.querySelectorAll('.bigProjIndividual > img'); const imgArray = Array.from(imgList); // or [].slice.call(imgList) const className = 'is--visible'; const toggle = node => () => { let desc = node.nextElementSibling; // or node.parentNode.querySelector('.bigProjDesc') if (desc) { desc.classList.toggle(className); // IE 10 + } } imgArray.forEach(img => { img.addEventListener('click', toggle(img)); }); 
 .bigProjDesc { display: none; } .bigProjDesc.is--visible { display: block; } 
 <div class="bigProjIndividual"> <img src="https://www.fillmurray.com/200/300" alt=""> <div class="bigProjDesc"> <h5>{{name}}</h5> <p>{{tech}}</p> <p>{{desc}}</p> <a href="{{web.github}}"target="_blank"> <img src="/github.png" alt="github"> </a> <a href="{{web.website}}"target="_blank"> <img src="/website.png" alt="github"> </a> </div> </div> 

Note: I changed your markup to make this example run in the browser. 注意:我更改了标记,以使此示例在浏览器中运行。 The code is given in ES6, but should be easy to translate into ES5 该代码在ES6中给出,但应该易于翻译成ES5

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

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