728x90
반응형

문제

주어진 코드를 이용하여 버튼을 누르면 텍스트가 나오고, 버튼을 다시 누르면 텍스트가 사라지게 만드시오.

<!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>
  <div class="obj">
    <div class="text">JAVASCRIPT 노잼</div>
    <button onclick="hide()">감추기</button>
  </div>
  <button class="btn" onclick="show()" style="display : none;">다시호출</button>
</body>
</html>
<script>
  // show();
  function hide(){
    var obj = document.querySelector('.obj');
    obj.style.display = 'none'; 
    var btn = document.querySelector('.btn');
    btn.style.display = 'block';
    
  }
  function show(){
    var obj = document.querySelector('.obj');
    obj.style.display = 'block'; 
    var btn = document.querySelector('.btn');
    btn.style.display = 'none';
  }
</script>

 

 

 

 

 

코드

	<style>
        #item {
            position:relative;
            width:500px;
            height:auto;
            padding:15px 20px;
            margin:auto;
            position: relative;
        }
        button {
            background-color:rgba(255,255,255,0.7);;
            padding:5px;
            border:1px solid #ccc;
            font-size:0.8em;			
        }
        .detail {
            width:400px;
            text-align:left;			
            line-height:1.8;
            display:none;
        }
        .btn {
            position: absolute;
            left: 30px;
            bottom: 30px;
        }
	</style>
<body>
    <div id="item">
        <img src="../img/flower.jpg" alt="">
        <button class="btn" onclick="show()">상세 설명 보기</button>
        <div id="desc" class="detail">
            <h4>등심붓꽃</h4>
            <p>북아메리카 원산으로 각지에서 관상초로 흔히 심고 있는 귀화식물이다. 길가나 잔디밭에서 흔히 볼 수 있다. 아주 작은 씨앗을 무수히 많이 가지고 있는데 바람을 이용해 씨앗들을 날려보내거나,
                뿌리줄기를 통해 동일한 개체들을 많이 만들어 냄으로써 번식한다. </p>
            <button onclick="hide()">상세 설명 닫기</button>
        </div>
    </div>
</body

 

<script>
    function show() {
        var btn = document.querySelector('.btn');
        var desc = document.querySelector('#desc');
        desc.style.display = "block";
        btn.style.display = "none";
    }

    function hide() {
        var btn = document.querySelector('.btn');
        var desc = document.querySelector('#desc');
        desc.style.display = "none";
        btn.style.display = "block";
    }
</script>
  • btn2 클래스에 none 속성을 주지 않아도 desc를 감추면 버튼도 같이 감춰진다.

 

 

 

▶ 함수 안을 간단하게 수정할 수 있다.

    function show() {
        var desc = document.querySelector('#desc').style.display = "block";
        var desc = document.querySelector('#desc').btn2.style.display = "block";
    }
728x90
반응형

+ Recent posts