Kobashi ロゴ

ニュース詳細detail_idだお

クリックで下にウインドウを開く
クリックで下にウインドウを開く

【 HTML 】

<!DOCTYPE html>

<html lang="ja">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>試作</title>

   

    <!--CSS-->

    <link rel="stylesheet" href="css/style.css">

   

</head>

<body>

    <!--本文-->

<details class="details">

    <summary class="details__summary">HTMLは要素を使います</summary>

    <div class="details__content">

        <p>要素を使う場合の開閉アニメーションはJavaScriptで補います。</p>

    </div>

</details>

    <!--JS-->

    <script src="js/main.js"></script>

</body>

</html>


【 CSS 】

/*body {

  margin: 50px 0 100px;

}*/


.details {

  line-height: 2;

  border: 1px solid #ced4da;

  width: 80%;

  margin: 0 auto 20px;

  border-radius: 10px;

  overflow: hidden;

}


.details__summary {

  position: relative;

  display: block;

  background-color: #f9f9f9;

  cursor: pointer;

  margin: 0;

  padding: 10px 40px 10px 20px;

  transition: background-color 0.3s ease;

}


.details__summary:hover {

  background-color: #f2f2f2;

}


.details__summary::-webkit-details-marker {

  display: none;

}


.details__summary::before {

  display: block;

  content: "";

  box-sizing: border-box;

  position: absolute;

  top: 50%;

  right: 20px;

  width: 8px;

  height: 8px;

  border: 0 solid transparent;

  border-bottom: 2px solid #6c757d;

  border-right: 2px solid #6c757d;

  transition: transform 0.1s ease-out;

  transform: translateY(-50%) rotate(45deg);

}


.details[open] .details__summary::before {

  transform: translateY(-50%) rotate(-135deg);

}


.details__content {

  overflow: hidden;

  margin: 0;

  padding: 0 20px;

  background-color: #fff;

}


.details__content > * {

  margin: 0;

  padding-top: 16px;

}


.details__content > *:last-child {

  padding-bottom: 16px;

}

【 JS 】

document.addEventListener('DOMContentLoaded', () => {

  const details = document.querySelectorAll('.details');


  details.forEach(element => {

    const summary = element.querySelector('.details__summary');

    const content = element.querySelector('.details__content');


    summary.addEventListener('click', e => {

      e.preventDefault();

      if (element.open) {

        const openDetails = content.animate(

          {

            opacity: [1, 0],

            height: [content.offsetHeight + 'px', 0],

          },

          {

            duration: 250,

            easing: 'ease-out',

          }

        );

        openDetails.onfinish = () => {

          element.removeAttribute('open');

        }

      } else {

        element.setAttribute('open', 'true');

        const openDetails = content.animate(

          {

            opacity: [0, 1],

            height: [0, content.offsetHeight + 'px'],

          },

          {

            duration: 250,

            easing: 'ease-out',

          }

        );

      }

    });

  });

});




前の記事次の記事