jQuery 특정 위치에서 요소 고정 오류
본문
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
ul {
list-style: none;
}
.inner {
max-width: 1500px;
margin: 0 auto;
}
section {
height: 100vh;
}
#box1,#box3{
background: salmon;
}
#box2 {
background: sandybrown;
}
header {
background: skyblue;
padding: 0 10rem;
height: 55px;
display: flex;
align-items: center;
justify-content: space-between;
position: fixed;
width: 100%;
}
header .gnb {
display: flex;
justify-content: space-between;
width: 400px;
}
.ec-base-tab ul {
display: flex;
font-size: var(--normal-font);
line-height: 14px;
word-break: break-all;
width: 500px;
}
.ec-base-tab ul.fixed {
position: fixed; top: 55px; left: 0; z-index: 9999;
}
.ec-base-tab ul li {
width: 25%;
text-align: center;
border: 1px solid #000;
border-right: none;
}
.ec-base-tab ul li:last-child {
border-right: 1px solid #000;
}
.ec-base-tab ul li a {
display: block;
padding: 10px;
color: inherit;
text-decoration: none;
}
</style>
</head>
<body>
<section id="box1">
<header>
<h1>header</h1>
<ul class="gnb">
<li>navi1</li>
<li>navi2</li>
<li>navi3</li>
<li>navi4</li>
</ul>
</header>
</section>
<section id="box2">
<div class="inner">
<div id="tabProduct" class="ec-base-tab" >
<ul>
<li class="selected"><a href="#prdDetail" target="_self">상세정보</a></li>
<li><a href="#prdInfo">구매안내</a></li>
<li><a href="#prdReview" name="use_review">상품후기</a></li>
<li><a href="#prdQnA" name="use_qna">Q&A</a></li>
</ul>
</div>
</div>
</section>
<section id="box3">
<div class="inner">
<div class="contentBox">
<p>content</p>
</div>
</div>
</section>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
const $tabProduct = $('#tabProduct ul');
$(document).ready(function(){
$(window).scroll(function(){
const $scrollTop = $(window).scrollTop();
const $tabProductHeight = $('#tabProduct ul').offset().top;
if($scrollTop >=$tabProductHeight) {
$tabProduct.addClass('fixed');
} else {
$tabProduct.removeClass('fixed');
}
})
});
</script>
</body>
</html>
#tabProduct ul 이 친구의 머리에 닿았을때 헤더와 함께 자연스럽게 고정되었으면 좋겠는데
계속 깜빡거리네요,,,,,
답변 1
$(window).scroll(function(){
const $hdheight = $("header").height();
const $scrollTop = $(window).scrollTop();
const $tabProductHeight = $('#tabProduct ul').offset().top;
if(!$tabProduct.hasClass("fixed")){
if($scrollTop >=$tabProductHeight) {
$tabProduct.addClass('fixed');
}
} else {
if($scrollTop <= $hdheight) {
$tabProduct.removeClass('fixed');
}
}
})
이걸로 해보세요
!-->