본문 바로가기
카테고리 없음

[HTML/CSS] Tailwind로 드롭박스 구현하기

by teamnova 2024. 4. 30.

안녕하세요 오늘은 Tailwind로 드롭박스를 구현해보겠습니다.

 

index.html 파일의 코드는 다음과 같습니다.

 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dropdown Menu Example</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@3.0.21/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 flex justify-center items-center h-screen">
    <div class="relative">
        <!-- 드롭다운 버튼 -->
        <button id="dropdownButton" class="bg-blue-500 text-white px-4 py-2 rounded focus:outline-none">메뉴</button>
        <!-- 드롭다운 컨텐츠, 기본적으로 숨겨져 있음 -->
        <div id="dropdownContent" class="hidden absolute w-48 bg-white rounded shadow mt-2">
            <!-- 드롭다운 항목들, 클릭 시 각각의 링크로 이동 -->
            <a href="#" class="block px-4 py-2 text-gray-800 hover:bg-blue-100">링크 1</a>
            <a href="#" class="block px-4 py-2 text-gray-800 hover:bg-blue-100">링크 2</a>
            <a href="#" class="block px-4 py-2 text-gray-800 hover:bg-blue-100">링크 3</a>
        </div>
    </div>
</body>
<script>
    // 드롭다운 메뉴와 버튼을 위한 요소를 선택
    const dropdownButton = document.getElementById('dropdownButton');
    const dropdownContent = document.getElementById('dropdownContent');

    // 드롭다운 버튼 클릭 이벤트 핸들러
    dropdownButton.addEventListener('click', function() {
        // 드롭다운 컨텐츠의 보이기/숨기기 상태를 토글
        dropdownContent.classList.toggle('hidden');
    });

    // 화면 어느 곳이든 클릭했을 때의 이벤트 핸들러
    window.addEventListener('click', function(e) {
        // 드롭다운 버튼 또는 컨텐츠 외부 클릭 시 드롭다운 숨기기
        if (!dropdownButton.contains(e.target) && !dropdownContent.contains(e.target)) {
            dropdownContent.classList.add('hidden');
        }
    });
</script>
</html>

 

 

구현 결과는 다음과 같습니다.