본문 바로가기

javascript(jquery)

[javascript/jquery] 스크롤시 상단 고정메뉴

 

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">
<style>
body {
  margin: 0px;
  padding: 0px;
}
.Menu {
  position: fixed;
  background-color: #0080ff;
}
.Content {
  margin: 50 auto;
}
</style>
</head>

<body>

<div>
  <h1>상단</h1>
</div>

<table class="Menu" width="2000" border="1">  
  <tr>
    <td width="1000">제목1</td>
    <td width="1000">제목2</td>
  </tr>
</table>

<table class="Content" width="2000" border="1">  
  <tr>
    <td width="1000">내용0</td>
    <td width="1000">내용0</td>
  </tr>
  <tr>
    <td>내용1</td>
    <td>내용2</td>
  </tr>     
</table>

<script type="text/javascript" src="./jquery/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$( document ).ready( function() {
	var Offset = $(".Menu").offset();
  var OffsetLeft = $(".Menu").offset().left;
  $(".Menu").css("top",Offset.top);
  $( window ).scroll( function() {
		$(".Menu").css("left",0-$(this).scrollLeft()+OffsetLeft);	
		if ($(this).scrollTop() > 0) //상하 스크롤
		{
			$(".Menu").css("top",0);
		}
		else //스크롤 최상단
		{
			$(".Menu").css("top",Offset.top);
		}
  });
});
</script>

</body>
</html>