使用javaScript隐藏和显示内容

时间:2019-11-11 10:13:27

标签: javascript html css

因此,在我的示例中,我有2个div按钮(分别名为btn1和btn2)和2个div元素(分别名为content1和content2)。

我想要的是,当您单击btn1时,将显示content1。如果您单击btn2,则应显示content2。

Content1和content2元素当前放置在同一位置,默认情况下,单击任何内容之前都不应该打开所有content元素。 我想用纯javaSript实现。

这是示例代码:

var btn1 = document.getElementById("btn1");
var content1 = document.getElementById("content1");
content1.style.opacity = "0";

btn1.addEventListener("mouseover", showContent1);

function showContent1(){
  if(content1.style.opacity === "0") {
    content1.style.opacity = "1";
  } else {content1.style.opacity = "0";}
}

var btn2 = document.getElementById("btn2");
var content2 = document.getElementById("content2");
content2.style.opacity = "0";

btn2.addEventListener("mouseover", showContent2);

function showContent2(){
  if(content2.style.opacity === "0") {
    content2.style.opacity = "1";
  } else {content2.style.opacity = "0";}
}
#btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;height:200px;border: 2px solid black;
}
#content1, #content2 {
width: 200px;height:200px;position:absolute;background:lightblue;
}
<div id="btn1">show1</div>
<div id="btn2">show2</div>
<div id="contents">
  <div id="content1">content 1</div>
  <div id="content2">content 2</div>
</div>

12 个答案:

答案 0 :(得分:3)

您可以将click事件添加到按钮,并基于被单击的按钮可以显示或隐藏相应的div。

<!DOCTYPE html>
    <html>

      <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>

    <style>
      #btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;
height:200px;
border: 2px solid black;
}
#content1, #content2 {
width: 200px;
height:200px;
position:absolute;
background:lightblue;
display:none;
}
    </style>
  </head>

  <body>

    <script>
      function showDiv(div){

        if(div == 'btn1'){
          document.getElementById('content1').style.display = 'block';
          document.getElementById('content2').style.display = 'none';
        }else{
          document.getElementById('content1').style.display = 'none';
          document.getElementById('content2').style.display = 'block';
        }
      }
    </script>
    <div id="btn1" onclick="showDiv('btn1')">show1</div>
<div id="btn2" onclick="showDiv('btn2')">show2</div>


<div id="contents">
  <div id="content1">content 1</div>
  <div id="content2">content 2</div>
</div>
  </body>

柱塞相同:https://plnkr.co/edit/brxoF2ClW2TeJOVMxn8d?p=preview     

答案 1 :(得分:2)

选中此选项,我使其具有动态性,因此您可以创建无限的按钮和内容。

function toogleContent(id){
  var toogleContent = document.getElementsByClassName('toogleContent');
  var i = toogleContent.length;
  while (i--) toogleContent[i].style.display = "none";
  document.getElementById(id).style.display = "block";
}
#btn1, #btn2 {
  width:100px;
  height:20px;
  text-align:center;
  background:grey;
  cursor:pointer;
  margin:10px 0px;
}
#contents {
  width: 200px;
  height:200px;
  border: 2px solid black;
}
#content1, #content2 {
  width: 200px;
  height:200px;
  position:absolute;
  background:lightblue;
  display:none;
}
<div id="btn1" class="toogleBtn" onclick="toogleContent('content1')">show1</div>
<div id="btn2" class="toogleBtn" onclick="toogleContent('content2')">show2</div>
<div id="contents">
  <div id="content1" class="toogleContent">content 1</div>
  <div id="content2" class="toogleContent">content 2</div>
</div>

答案 2 :(得分:1)

document.getElementById('btn1').addEventListener('click', ()=>{
                document.getElementById('content2').style.display = "none";
                document.getElementById('content1').style.display = "block";
            });
    document.getElementById('btn2').addEventListener('click', ()=>{
                document.getElementById('content1').style.display = "none";
                document.getElementById('content2').style.display = "block";
            });
#btn1, #btn2 {
    width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
    }
    #contents {
    width: 200px;height:200px;border: 2px solid black;
    }
    #content1, #content2 {
    width: 200px;height:200px;position:absolute;background:lightblue;display:none;
    }
<div id="btn1">show1</div>
    <div id="btn2">show2</div>
    <div id="contents">
      <div id="content1">content 1</div>
      <div id="content2">content 2</div>
    </div>

答案 3 :(得分:1)

您需要onClick事件和2个条件。请检查一下,

function showContent(content_id) {

  if (content_id == 'content1') {
    document.getElementById('content1').style.display = 'block';
    document.getElementById('content2').style.display = 'none';
  } else if (content_id == 'content2') {
    document.getElementById('content1').style.display = 'none';
    document.getElementById('content2').style.display = 'block';
  }
  

}
#btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;height:200px;border: 2px solid black;
}
#content1, #content2 {
width: 200px;height:200px;position:absolute;background:lightblue; display:none;
}
<div id="btn1" onClick='showContent("content1")'>show1</div>
<div id="btn2" onClick='showContent("content2")'>show2</div>
<div id="contents">
  <div id="content1">content 1</div>
  <div id="content2">content 2</div>
</div>

答案 4 :(得分:1)

这是使用香草javascript的简单方法,只需添加一种方法即可根据您单击的按钮隐藏/显示元素

function toogle(showelem, hideelem) {
      document.getElementById(showelem).style.display = "block";
      document.getElementById(hideelem).style.display = "none";
    }
#btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;height:200px;border: 2px solid black;
}
#content1, #content2 {
width: 200px;height:200px;position:absolute;background:lightblue;
}
<div id="btn1" onClick="toogle('content1','content2');">show1</div>
<div id="btn2" onClick="toogle('content2','content1');">show2</div>
<div id="contents">
  <div id="content1">content 1</div>
  <div id="content2">content 2</div>
</div>

答案 5 :(得分:1)

function myFunction() {
  var element = document.getElementById("myDIV");
  element.classList.remove("displayblock");
}
function myFunctionShow(){
  var element = document.getElementById("myDIV");
  element.classList.add("displayblock");
}
.mystyle {
  width: 100%;
  padding: 25px;
  background-color: coral;
  color: white;
  display:none;
}
.displayblock{
  display:block;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<p>Click the "Try it" button to remove the "mystyle" class from the DIV element:</p>

<button onclick="myFunction()">Hide</button>

<button onclick="myFunctionShow()">Show</button>

<div id="myDIV" class="mystyle displayblock">
This is a DIV element.
</div>



</body>
</html>

答案 6 :(得分:1)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #btn1,
        #btn2 {
            width: 100px;
            height: 20px;
            text-align: center;
            background: grey;
            cursor: pointer;
            margin: 10px 0px;
        }

        #contents {
            width: 200px;
            height: 200px;
            border: 2px solid black;
        }

        #content1,
        #content2 {
            width: 200px;
            height: 200px;
            position: absolute;
            background: lightblue;
        }
    </style>
</head>

<body>

    <div id="btn1" onclick="showdiv1()">show1</div>
    <div id="btn2" onclick="showdiv2()">show2</div>
    <div id="contents">
        <div id="content1">content 1</div>
        <div id="content2">content 2</div>
    </div>
</body>

<script>
   function showdiv1(){
       console.log( document.getElementById('content1'))
        document.getElementById('content1').style.display='block';
        document.getElementById('content2').style.display='none';
    }

    function showdiv2(){
        document.getElementById('content1').style.display='none';
        document.getElementById('content2').style.display='block';
    }
</script>

</html>

我们在这里

您可以通过此操作隐藏和显示任何元素

element.style.display = 'none';           // Hide
element.style.display = 'block';          // Show
element.style.display = 'inline';         // Show
element.style.display = 'inline-block';   // Show

答案 7 :(得分:0)

上述答案都是正确的,只要它们能使您从A升级到B(根据您提供的代码),还应在代码中使用一些“最佳实践”更改,以避免常见的变化陷阱(并允许更好的可维护性和代码重用)。

首先,应避免使用ID进行样式设置。尽管不鼓励使用ID来应用样式,但这样做是完全有效的(并且不会破坏任何内容)。页面的ID在文档中必须始终是唯一的,因此使用它来设置多个相似元素的样式意味着您将很快拥有损坏的HTML(通过重新使用ID)或笨拙且不可维护的样式表(通过具有多个相同的样式)选择器)。您应该更喜欢使用类为元素添加样式,因为您可以重用类,甚至可以扩展或对每个元素使用多个类。

在我的代码段中,我还使用了一个带有数字的数据集,以帮助确定正在“选择”哪个元素。数据集旨在存储自定义数据,并且对于在JavaScript中存储和检索数据非常有用。通过使用数据集来存储与元素的ID或类无关的ID,您可以无限地添加/删除选项卡,而不必更改CSS或JavaScript以使其适合。毕竟,我可以添加ID为3的数据集(例如<div class="button" data-id="3">),而button的样式也不会受到影响。

其他良好做法包括:与用于样式化元素的类名或选择器相比,为JavaScript使用单独的类名或选择器(再次使您可以在不影响元素外观的情况下更改JavaScript选择器的名称-您还可以在JavaScript之前添加前缀像我所做的那样,将选择器与js-一起使用,这样很明显选择器是由JavaScript使用的,而不是用于设置元素样式的。)

我还使用了BEM样式指南来命名我的类(尽管这是一种偏爱,尽管总之,选择并使用某种命名约定或样式指南进行命名/样式元素)。

最终建议(未显示)<button>元素,而不是按钮的<div>。这将改善您对网站的访问权限,因为屏幕阅读器技术可以区分什么是按钮和什么仅仅是内容块(毕竟,屏幕阅读器可能不会发现<div>拥有一个按钮click事件处理程序已添加,因此禁用的用户可能不知道他们可以单击“按钮”以切换标签。

// Select all buttons using querySelectorAll
let buttons = document.querySelectorAll('.js-toggle');

// Loop through each button and add an event listener
Array.from(buttons).forEach(button => {
  // Click event listener
  button.addEventListener('click', function() {
     // Select all elements to hide/show
     let tab_contents = document.querySelectorAll('.js-content');
      
     // Hide all elements
     hideElems(tab_contents);
     
     // Get ID of button
     let id = this.dataset.id;
     
     // Select relevant tab using the ID above
     document.querySelector(`.js-content-${id}`).style.display = 'block';
  });
});

// Function for hiding all elements
let hideElems = (elems) => {
  Array.from(elems).forEach(elem => elem.style.display = 'none');
}
.button {
  width: 100px;
  height: 20px;
  text-align: center;
  background: grey;
  cursor: pointer;
  margin: 10px 0;
}

.tabs {
  width: 200px;
  height: 200px;
  border: 2px solid black;
}

.tabs__content {
  width: 200px;
  height: 200px;
  background: lightblue;
  display: none;
}
<div class="button js-toggle" data-id="1">show1</div>
<div class="button js-toggle" data-id="2">show2</div>

<div class="tabs">
  <div class="tabs__content js-content js-content-1">content 1</div>
  <div class="tabs__content js-content js-content-2">content 2</div>
</div>

答案 8 :(得分:0)

如果我理解的正确,则应默认设置“显示:无”,然后处理单击按钮以切换“打开”类。参见下面的示例。

const btn1 = document.getElementById("btn1"),
	  btn2 = document.getElementById("btn2"),
	  content1 = document.getElementById("content1"),
	  content2 = document.getElementById("content2");

const map = new Map()
	.set(btn1, content1)
        .set(btn2, content2);

const closeMapContent = _ => 
  map.forEach((value, key) => value.classList.remove("open"));

map.forEach((value, key) => {
	key.addEventListener("click", event => {
  	closeMapContent();
  	value.classList.add("open");
  })
});
#btn1, #btn2 {
  width: 100px;
  height: 20px;
  text-align: center;
  background: grey;
  cursor: pointer;
  margin: 10px 0px;
}
#contents {
  width: 200px;
  height: 200px;
  border: 2px solid black;
}
#content1, #content2 {
  width: 200px;
  height: 200px;
  position: absolute;
  background: lightblue;
  display: none;
}

.open {
  display: block !important;
}
<div id="btn1">show1</div>
<div id="btn2">show2</div>
<div id="contents">
  <div id="content1">content 1</div>
  <div id="content2">content 2</div>
</div>

答案 9 :(得分:0)

begin work;

DECLARE 

    cur_films CURSOR
       FOR select CURRENT_DATE + i date_
       FROM  generate_series(date '2019-11-11'- CURRENT_DATE,  date '2019-11-15' - CURRENT_DATE ) i;
       fetch forward 2 from cur_films;

close cur_films;

commit work; 
function show() {
          const h = document.getElementById('hidden1');
          h.style.display = 'block' ;
          const s =document.getElementById('showed');
          s.style.display = 'none';
        }
        function hide() {
            const h = document.getElementById('hidden1');
            h.style.display = 'none' ;
            const s =document.getElementById('showed');
            s.style.display = 'block';
        }

查看摘要

答案 10 :(得分:0)

解决此问题的另一种方法是使用data- *属性,且样式很少。您可以更改父div的属性,然后使用CSS将更改反映在子项上。

此外,如果知道子元素的数量,则无需遍历元素。

请参见以下示例:

function toogleContent(target) {
  document.querySelector("#contents").setAttribute("data-show", target);
}
#btn1,
#btn2 {
  width: 100px;
  height: 20px;
  text-align: center;
  background: grey;
  cursor: pointer;
  margin: 10px 0px;
}

#contents {
  width: 200px;
  height: 200px;
  border: 2px solid black;
}

#content1,
#content2 {
  width: 200px;
  height: 200px;
  position: absolute;
  background: lightblue;
  opacity: 0;
}

#contents[data-show='1']>#content1 {
  opacity: 1;
}

#contents[data-show='2']>#content2 {
  opacity: 1;
}
<div id="btn1" onclick="toogleContent(1)">show1</div>
<div id="btn2" onclick="toogleContent(2)">show2</div>
<div id="contents" data-show=''>
  <div id="content1">content 1</div>
  <div id="content2">content 2</div>
</div>

答案 11 :(得分:0)

  

https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

const buttons = document.querySelectorAll('.button');
const content = document.querySelector('.content__wrapper');

function init() {
  hideAll();
  setUpClickHandlers();
}

function hide(element) {
  element.classList.add('hide');
}

function show(element) {
  element.classList.remove('hide')
}

function hideAll() {
  Array.from(content.children).forEach(hide);
}

function toggle(element) {
  hideAll();
  show(element)
}

function onClick(content) {
  return () => toggle(content)
}

function setUpClickHandlers() {
  Array.from(buttons).forEach(element => {
    const show = content.querySelector(`.${element.dataset.for}`);
    element.addEventListener('click', onClick(show));
  });
}

init()
.hide {
  display: none
}

.button {
  height: 30px;
  line-height: 30px;
  border-radius: 5px;
  border: 1px solid grey;
  padding: 0 10px;
  display: inline-block;
  margin: 10px 0;
}

.content__wrapper {
  background-color: aqua;
  padding: 16px;
}
<div class="button" data-for="content_1">content 1</div>
<div class="button" data-for="content_2"> content 2</div>
<div class="button" data-for="content_3"> content 3</div>
<div class="button" data-for="content_4"> content 4</div>


<div class="content__wrapper">
  <div class="content content_1">Content 1</div>
  <div class="content content_2">Content 2</div>
  <div class="content content_3">Content 3</div>
  <div class="content content_4">Content 4</div>
</div>