如何使用JS在按钮单击上显示不同的div? [英] how to display different div on button click with JS?

查看:42
本文介绍了如何使用JS在按钮单击上显示不同的div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个区域,其中有2张卡片,每张卡片上都有一个按钮和一个小的描述性文字.我想要实现的是,当我单击按钮3时,发生了以下事情:

I am trying to make a section where there are 2 cards, each one with a button and a small descriptive text. What I am trying to achieve is that when I click on the button 3 things happen:

1按钮更改内容,该内容从"+"开始.改为-",但这是我最不担心的地方.

1 The button changes content, that goes from a "+" to a "-", but that is what worries me the least.

2显示带有与该卡相对应的信息的div并占用100 vw和

2 that a div is displayed with information corresponding to that card and that occupies 100 vw and

3如果显示一个div并单击另一张卡上的另一个按钮,则第一个div消失,第二个div出现并占用100vw

3 that if there is a div displayed and the other button on another card is clicked, the first div disappears and the second appears and occupies the 100vw

-----我在用什么?我正在使用HTML5,CSS,Vanilla Js,Bootstrap(主要用于CSS)-----

-----What am I using? I am using HTML5, CSS, Vanilla Js, Bootstrap (mainly for the css)-----

这是我想要实现的:

这是我所取得的成就:

var jsaccordion = {
    init : function (target) {  
      var headers = document.querySelectorAll("#" + target + " .accordion-btn");
      if (headers.length > 0) { for (var head of headers) {
        head.addEventListener("click", jsaccordion.select);
      }}
    },

    select : function () {        
      this.classList.toggle("open");
    }
  };
  window.addEventListener('load', function(){
    jsaccordion.init("accordion-container");
  });

.accordion-text {
  display: none;
  color: #808080;
  padding: 15px;
  border: 1px solid #ffcc4b;
}
.accordion-btn.open + .accordion-text{
  display: block;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

<div class='row'>
<div id="accordion-container" class='col-6'>
    <div class="my-3">
      <h3 class=" text-center">First one</h3>
      <button class='mx-auto d-block accordion-btn btn btn-white border-primary'>+</button>
         <div class="accordion-text">
            <p>
some specific and special information for the first div.</p>
         </div>
     </div>
</div>
           
<div id="accordion-container" class='col-6'>
    <div class="my-3">
      <h3 class='text-center'>second one</h3>
       <button class='mx-auto d-block accordion-btn btn btn-white border-primary'>+</button>
        
         <div class="accordion-text">
            <p>some specific and special information for the second div.</p>
         </div>
     </div>
</div>
          
</div>

请帮助我,我不知道该怎么做

Please help me, I don't know how to do it

推荐答案

在jQuery中执行此操作要容易得多,但这是我使用Vanilla JS的方法.

It is a lot easier to do this in jQuery, but here is how I would approach it using Vanilla JS.

  • 这个想法是要使既不基于元素又基于浏览器窗口的内容居中,是使用共享容器(在任一元素之外)进行打印.这也使猜测工作不再需要定位.
  • 单击按钮后,应从手风琴中复制信息,并将其打印到目标容器中.同样在该单击上,检查另一个是否处于活动状态以删除 active 类.使用CSS伪元素将类添加到活动容器中,以更改按钮符号 + -.
  • 将箭头保留在手风琴容器中也将使其更容易根据其所在的HTML元素进行定位.
  • 旁注:您应该在整个页面上仅使用一次HTML ID,否则对多个实例使用一个类.这是指#accordion-container .
  • The idea is that to center something that is based on neither elements, but moreso the browser window, is to use a shared container (outside of either element) to print to. This takes the guess work out of positioning as well.
  • On clicking the button, the information should be copied from the accordion, and printed to the target container. Also on that click, check if the other is active to remove the active class. Adding classes to the active container to change the button symbol + and -, using CSS pseudo-elements.
  • Keeping the arrows inside the accordion containers will also make it easier to position them according to the HTML element it is in.
  • Sidenote: You should only use an HTML ID once on the entire page, otherwise use a class for multiple instances. This is in reference to #accordion-container.

var sharedCont = document.getElementById('shared-container');
var allCont = document.querySelectorAll('#accordion-container');

var jsaccordion = {
    init : function (target) {  
        var headers = document.querySelectorAll("#" + target + " .accordion-btn");
        if (headers.length > 0) { for (var head of headers) {
            head.addEventListener("click", jsaccordion.select);
        }}
    },

    select : function () {        
        var targ1 = this.parentElement.closest('#accordion-container'), // find parent
            targText = targ1.querySelector('.accordion-text').innerHTML; // grab text for shared container

        if( targ1.classList.contains('active') ){ 

            // when clicked, if active, reset them all
            targ1.classList.remove('active');
            sharedCont.innerHTML = '';
            sharedCont.classList.remove('active');

        } else {
            // when clicked, reset them all, then activate
            for (let i = 0; i < allCont.length; i++) {
                var el = allCont[i];
                el.classList.remove('active');
            }

            targ1.classList.add('active');
            sharedCont.innerHTML = targText;
            sharedCont.classList.add('active');

        }
    }
};
window.addEventListener('load', function(){
    jsaccordion.init("accordion-container");
});

body {
    max-width: 90%;
    margin: 0 auto;
    overflow: hidden;
}
#accordion-container {
    position: relative;
}
#accordion-container button::before {
    content: '+' !important;
}
#accordion-container.active button::before {
    content: '-' !important;
}
#accordion-container.active::after {
    content: '';
    width: 0; 
    height: 0; 
    border-left: 15px solid transparent;
    border-right: 15px solid transparent;
    border-bottom: 15px solid orange;
    position: absolute;
    bottom: -2rem;
    left: 50%;
    transform: translateX(-50%);
    color: orange;
    z-index: 100;
    font-size: 3rem;
    line-height: 1;
}
#accordion-container .accordion-text {
    display: none;
    color: #808080;
    padding: 15px;
    border: 1px solid #ffcc4b;
}
/* .accordion-btn.open + .accordion-text{
    display: block;
} */

#shared-container {
    margin-top: 2rem;
    display: block;
    width: 100%;
    padding: 2rem;
    border: 1px solid orange;
    display: none;
}
#shared-container.active {
    display: block;
    text-align: center;
}
#shared-container p {
    margin: 0;
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Testing testing testing</h1>

    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

    <div class='row'>
        <div id="accordion-container" class='col-6'>
            <div class="my-3">
            <h3 class=" text-center">First one</h3>
            <button class='mx-auto d-block accordion-btn btn btn-white border-primary'></button>
                <div class="accordion-text">
                    <p>Egestas erat imperdiet sed euismod nisi porta. Ipsum dolor sit amet consectetur adipiscing. Maecenas pharetra convallis posuere morbi leo urna molestie. Nullam vehicula ipsum a arcu. Gravida cum sociis natoque penatibus et magnis. Duis convallis convallis tellus id interdum velit laoreet. </p>
                </div>
            </div>
        </div>
                
        <div id="accordion-container" class='col-6'>
            <div class="my-3">
            <h3 class='text-center'>second one</h3>
            <button class='mx-auto d-block accordion-btn btn btn-white border-primary'></button>
                
                <div class="accordion-text">
                    <p>Tempus egestas sed sed risus pretium quam vulputate dignissim. Risus at ultrices mi tempus imperdiet. Mauris pellentesque pulvinar pellentesque habitant morbi tristique senectus et. Nisl vel pretium lectus quam id leo.</p>
                </div>
            </div>
        </div>
                
    </div>
    <div id="shared-container"></div>
</body>
</html>

这篇关于如何使用JS在按钮单击上显示不同的div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆