Skip to content

CHICPRO

  • Life Log
  • Cycling Log
  • Photo Log
    • Portrait
    • Landscape
    • Flower
    • Etc
  • Coding Log
  • Information

jQuery 모바일 브라우저 상단 플로팅 메뉴

2013-10-14 by 편리

이전에 모바일에서 사용할 플로팅 메뉴 작업을 하고 있다고 했는데 그 작업이 어느정도 마무리 됐고 코드도 정리가 돼서 드디어 공개를 하고자 한다. 대단한 스크립트는 아니지만 혼자 생각하고 고민해서 의도했던대로 완료가 됐다는 것은 아무리 사소한 것이라도 기분이 좋을 수 밖에 없다. 이런 것때문에 개발에 몰두하게 되는 것인지도 모르겠다. 모든 모바일 기기에서 테스트한 것은 아니지만 다른 분들의 도움을 받아 많이 쓰는 기기에서 테스트해봤을 때 문제점은 발견되지 않았다. 상단 플로팅 메뉴와 함께 하단 플로팅 메뉴도 작업을 했는데 하단 플로팅 메뉴관련 스크립트는 다음에 포스팅할 예정이다. 플로팅 메뉴는 http://codepub.net/floatmenu/ 에서 확인할 수 있다. 모바일 환경만을 고려했기 때문에 IE 등에서는 오류가 발생한다. 다만 크롬, 파이어폭스 IE10에서는 작동하는 것을 확인할 수 있다.

우선 css와 문서 구조는 아래와 같다.

body { margin: 0; padding: 0; }
#topFloatMenu { display:none; position:absolute; top:0; left:0; z-index: 100; width:100%; height: 60px; line-height: 60px; text-align: center; background-color: #eee; }
#bottomFloatMenu { display:none; position:absolute; top:0; left: 0; z-index: 100; width: 100%; height: 60px; line-height: 60px; text-align: center; background-color: #eee; }
#Content { width: 100%; height: 2000px; }

 

<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=0,maximum-scale=10">
<meta name="HandheldFriendly" content="true">
<title>모바일 플로팅 메뉴 테스트</title>
<link rel="stylesheet" href="./css/style.css">
<script src="./js/jquery-1.8.3.min.js"></script>
<script src="./js/jquery.floatmenu.min.js"></script>
</head>
<body>
<div id="topFloatMenu">상단 메뉴</div>
<div id="Content">컨텐츠</div>
<div id="bottomFloatMenu">하단메뉴</div>

<script>
$(function() {
    $("#topFloatMenu").topFloatMenu();
});
</script>
</body>
</html>

위 코드에서  $(“#topFloatMenu”).topFloatMenu(); 부분이 스크립트를 실행시키는 부분이다. 이제 상단 플로팅 메뉴를 처리하는 스크립트 코드이다.

(function($) {
    $.fn.topFloatMenu = function(timeout, duration, interval, count)
    {
        var cfg = {
                timeout: 200,
                duration: 300,
                interval: 500,
                count: 5
            };

        if(typeof timeout == "object") {
            cfg = $.extend( cfg, timeout);
        } else {
            if(timeout) {
                cfg = $.extend({ timeout: timeout });
            }

            if(duration) {
                cfg = $.extend({ duration: duration });
            }

            if(interval) {
                cfg = $.extend({ interval: interval });
            }

            if(count) {
                cfg = $.extend({ count: count });
            }
        }

        var $menu = this;
        var scroll_y = 0;
        var origin_y = 0;
        var timeout = null;
        var interval = null;
        var height = parseInt($menu.height());
        var interval_count = 0;

        function init_menu()
        {
            hide_menu();

            timeout = setTimeout(function() {
                $menu.css("top", (scroll_y - height)+"px").css("display", "block");
                $menu.animate({ top: scroll_y }, cfg.duration);

                return;
            }, cfg.timeout);
        }

        function float_menu()
        {
            hide_menu();

            origin_y = $(window).scrollTop();

            timeout = setTimeout(function() {
                scroll_y = $(window).scrollTop();

                if(origin_y == scroll_y) {
                    $menu.css("top", (scroll_y - height)+"px").css("display", "block");
                    $menu.animate({ top: scroll_y }, cfg.duration);
                }
            }, cfg.timeout);
        }

        function hide_menu()
        {
            $menu.css("display", "none").clearQueue().stop().css("top", "-"+height+"px");

            clearTimeout(timeout);
            clearInterval(interval);

            interval_count = 0;
            interval = setInterval(check_menu, cfg.interval);
        }

        function check_menu()
        {
            clearTimeout(timeout);

            if(interval_count == parseInt(cfg.count)) {
                clearInterval(interval);
                interval_count = 0;
                return;
            } else {
                interval_count++;
            }

            origin_y = $(window).scrollTop();

            timeout = setTimeout(function() {
                scroll_y = $(window).scrollTop();

                if(origin_y == scroll_y) {
                    element_y = parseInt($menu.css("top"));

                    if(!$menu.is(":animated") && ($menu.is(":hidden") || (element_y - scroll_y) != 0)) {
                        float_menu();
                    }
                }
            }, cfg.timeout);
        }

        $(window).on("scroll",function(event) {
            float_menu();
        });

        $(window).on("resize", function(event) {
            if(origin_y != scroll_y)
                float_menu();
        });

        $(window).on("load", function(event) {
            init_menu();
        });

        document.addEventListener('touchmove', function(event) {
            hide_menu();
        }, false);
    }
}(jQuery));

setTimeout을 이용해 스크롤이 진행 중일 때는 메뉴를 보이지 않도록 하고 스크롤이 멈춘 것은 이전 위치와 현 위치가 일치하지는지로 체크하고 있다. 기기에 따라서 메뉴가 숨겨진 상태에서 다시 나타나지 않는 경우가 있어 setInterval을 이용해서 0.5초 간격으로 메뉴가 보이는지 체크해서 보이지 않으면 메뉴를 보이도록 했고 Interval은 5번 실행되면 멈추도록 했다. 계속 실행되면 기기에 무리가 가지 않을까 싶어서였다.

Post navigation

Previous Post:

문서편집기 에디트플러스(EditPlus) 버전 3.51 패치 빌드 1350

Next Post:

JavaScript를 이용해 좌우 swipe 방향 알아내기

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

  • php 배열 연산에서 + 와 array_merge 의 차이
  • pcntl_fork 를 이용한 다중 프로세스 실행
  • 아이폰 단축어를 이용하여 주중 공휴일엔 알람 울리지 않게 하기
  • 구글 캘린더 전체일정 재동기화
  • OpenLiteSpeed 웹서버에 HTTP 인증 적용
  • OpenLiteSpeed 웹어드민 도메인 연결
  • WireGuard를 이용한 VPN 환경 구축
  • Ubuntu 22.04 서버에 OpenLiteSpeed 웹서버 세팅
  • 맥 vim 세팅
  • 우분투 시스템 터미널쉘 zsh 로 변경

Recent Comments

  • 편리 on 업무관리용 그누보드 게시판 스킨
  • 임종섭 on 업무관리용 그누보드 게시판 스킨
  • 캐논 5D 펌웨어 | Dslr 펌웨어 업그레이드 방법 82 개의 베스트 답변 on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • Top 5 캐논 5D 펌웨어 Top 89 Best Answers on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • 편리 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 임팀장 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 편리 on Notepad++ NppFTP 플러그인 수동 설치
  • paul-j on Notepad++ NppFTP 플러그인 수동 설치
  • YS on Windows 10 iCloud 사진 저장 폴더 변경
  • 편리 on Docker를 이용한 Centos7 + httpd + php 5.4 개발환경 구축

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
© 2025 CHICPRO | Built using WordPress and SuperbThemes