html&php

탭 메뉴 · 마우스를 메뉴에 올리면 자동으로 내용 나오게 하기

Zyss 2023. 4. 5. 17:01
반응형

<style>

    .tab-content {
        display: none;
    }
    .tab-content.active {
        display: block;
    }
    .tab-menu li {
        display: inline-block;
        margin-right: 10px;
        cursor: pointer;
        width:100px;
        padding: 20px;
        border: 1px solid #ccc;
        border-bottom: none;
    }
    .tab-menu li.active, .tab-menu li:hover {
        background-color: #f5f5f5;
        border-bottom: 1px solid #fff;
    }
</style>
<ul class="tab-menu">
    <li class="active" data-tab="tab1">Tab 1</li>
    <li data-tab="tab2">Tab 2</li>
</ul>

<div class="tab-container">
    <div id="tab1" class="tab-content active">
        <p>This is tab content 1</p>
    </div>
    <div id="tab2" class="tab-content">
        <p>This is tab content 2</p>
    </div>
</div>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<script type="text/javascript">
    $(document).ready(function() {
        // Tab menu click event
        $('.tab-menu li').on('click', function() {
            // Remove the active class from all tabs
            $('.tab-menu li').removeClass('active');
            // Add the active class to the clicked tab
            $(this).addClass('active');
            // Get the data-tab attribute value of the clicked tab
            var tabId = $(this).attr('data-tab');
            // Hide all tab contents
            $('.tab-content').removeClass('active');
            // Show the tab content of the clicked tab
            $('#'+tabId).addClass('active');
        });

        // Tab menu hover event
        $('.tab-menu li').on('mouseenter', function() {
            // Get the data-tab attribute value of the hovered tab
            var tabId = $(this).attr('data-tab');
            // Hide all tab contents
            $('.tab-content').removeClass('active');
            // Show the tab content of the hovered tab
            $('#'+tabId).addClass('active');
            // Add the active class to the hovered tab
            $('.tab-menu li').removeClass('active');
            $(this).addClass('active');
        });

        // Tab menu mouseout event
        $('.tab-menu li').on('mouseleave', function() {
            // Hide all tab contents
            $('.tab-content').removeClass('active');
            // Show the content of the active tab
            var activeTabId = $('.tab-menu li.active').attr('data-tab');
            $('#'+activeTabId).addClass('active');
        });
    });
	</script>
반응형