Почему мое адаптивное CSS-меню заставляет контент страницы прыгать вверх?

0

У меня есть меню навигации, которое расположено относительно других элементов в моем коде. Когда вы просматриваете это меню навигации в браузере с минимальной шириной 200 пикселей max 767px и откройте меню навигации, все содержимое будет нажато вниз, что хорошо, так как вы можете просмотреть весь контент, однако, если вы начните прокрутку вниз при открытии меню, содержимое страницы скачет вверх, по крайней мере, 400+ пикселей, не позволяя никому читать 1/4 содержимого на странице.

У меня есть сценарий, который заставляет это меню навигации входить в верхнюю часть браузера, и когда я отключу этот скрипт и повторю вышеуказанные действия, все в порядке; контент не перескакивает и т.д. Единственная проблема в том, что меню навигации больше не прилипает к верхней части страницы, а когда открыто навигационное меню, оно не выталкивает контент вниз, оно закрывается расширяющимся меню навигации,

Я приложил рабочую скрипку, которая реплицирует проблему. http://jsfiddle.net/y7Cgg/1/

Любое средство для этого сценария?

скрипт

$(document).ready(function(){
    $(this).scrollTop(0);
});

$(window).scroll(function()
{
    if( $(window).scrollTop() > 36 )
    {
        $('.mobile-nav-container').css({position: 'fixed'});
    } 
    else 
    {
        $('.mobile-nav-container').css({position: 'relative', top: '-3px'});
    }
});

HTML

<div id="main-image2"></div>

<!----------------------------MOBILE NAVIGATION MENU----------------------------------->
<div class="mobile-nav-container">
<div id="main-logo-mobile"><a href="index.html"><img src="images/mobile-logo.svg" width="32px" alt="3Elements Review, a literary journal based in Chicago, Illinois. This is our magazine mobile logo." border="none" id="main-logo-mobile"></a></div>
<button class="open-menu"><img src="images/menu-button.svg"></button>
<button class="open-menu-small"><img src="images/menu-button-small.svg"></button>
<nav class="nav-menu">
<div class="home-btn-mobile"><a href="index.html"><img src="images/home.svg" width="20px" alt="3Elements Review, a literary journal based in Chicago, Illinois." border="none" id="home-btn"></a></div>
<ul class="nav-menu">
<li class="mb-nav"><a href="current-journal.html">CURRENT JOURNAL</a></li>
<li class="mb-nav"><a href="subscribe.html">SUBSCRIBE</a></li>
<li class="mb-nav"><a href="submit.html">SUBMIT MATERIAL</a></li>
<li class="mb-nav"><a href="submission-guidelines.html">SUBMISSION GUIDELINES</a></li>
<li class="mb-nav"><a href="http://3elementsreview.blogspot.com">3E BLOG</a></li>
<li class="mb-nav"><a href="past-journals.html">PAST JOURNALS</a></li>
<li class="mb-nav"><a href="about-3elements.html">ABOUT 3ELEMENTS</a></li>
<li class="mb-nav"><a href="the-editors.html">THE EDITORS</a></li>
<li class="mb-nav"><a href="contact.html">CONTACT</a></li>
</ul>
</nav>
</div><!----------------------MOBILE NAV CONTAINER  END------------------------------->


<h1 class="image-header">USAGE RIGHTS</h1>
<div id="main-logo"><a href="index.html"><img src="images/logo.svg" width="100%" alt="3Elements Review, a literary journal based in Chicago, Illinois. This is our magazine logo." border="none" id="main-logo"></a></div>
<h2 class="image-sub-head"></h2>

<nav class="container">
<ul>
<li class="home-btn"><a href="index.html"><img src="images/home.svg" width="37px" alt="3Elements Review, a literary journal based in Chicago, Illinois." border="none" id="home-btn"></a></li>
<li class="current" style="background-color:#313131;"><a href="current-journal.html" class="current">CURRENT JOURNAL<span class="sub-nav">Our latest and greatest!</span></a></li>
<li class="submit" style="background-color:#404040;"><a href="submit.html" class="current">SUBMIT<span class="sub-nav">Your writing</span></a></li>
<li class="guidelines" style="background-color:#505050;"><a href="submission-guidelines.html" class="current">SUBMISSION GUIDELINES<span class="sub-nav">Everything you need to know is here</span></a></li>
<li class="blog" style="background-color:#4b4b4b;"><a href="3eblog.html" class="current">BLOG<span class="sub-nav">Just a blog</span></a></li>
<li class="past" style="background-color:#404040;"><a href="past-journals.html" class="current">PAST JOURNALS<span class="sub-nav">Browse our issue archives</span></a></li>
<li class="about" style="background-color:#313131;"><a href="about-3elements.html" class="current">ABOUT 3E<span class="sub-nav">What we're about</span></a></li>
</ul>
</nav>
</div><!-----------------------------MAIN IMAGE  END----------------------------------->


<div id="container"><!------------------------CONTAINER THAT SURROUNDS ALL CONTENT BELOW THE NAVIGATION BAR------------------------------->


<header>
<h1 class="page-headline">Usage Rights in our Journal</h1>
</header>

<section>
<article>
<p class="usage-rights">If <em>3Elements Review</em> decides to publish your work, we ask for first-time publishing rights. Afterward, the rights are reverted back to you. If your work is reprinted elsewhere, we ask that you reference <em>3Elements Review</em> as the original publisher. We also request the right to archive your work permanently. We reserve the right to include your work on our website, in printed form, and in collections of work acquired from our past issues, such as annual anthologies.</p>

<p class="usage-rights"><em>3Elements Review</em> retains no rights on submitted artwork and images; rights belong to the artist/photographer. However, by submitting your artwork or photography, you agree to allow <em>3Elements Review</em> to display your work on any of the following: 3elementsreview.com, <a href="https://twitter.com/3ElementsReview" class="p-social" target="_blank">Twitter</a>, and <a href="https://www.facebook.com/pages/3Elements-Review/165239120323115" class="p-social" target="_blank">Facebook</a>. If used in any of the aforementioned forms, your artwork/photos will always be credited to you.</p>

<p class="usage-rights">We reserve the right to modify the accepted work in terms of punctuation, word usage, spelling, and capitalization, with permission from the author. If the author declines the changes, we reserve the right to revert our decision to publish.</p>

<p class="usage-rights">The author confirms that the work is wholly original, does not violate or infringe upon the copyright or privacy of any other person or company whatsoever, and that they, the author, are the sole owner and creator of the work to be published.</p>
</article>

</section>


<footer class="bottom-footer">
<div id="nav-arrow"><img src="images/nav-arrow.svg" width="35%"><br><span class="arrow-text" style="width:100px; color:#f8f4ec; font-family:myriad pro, arial, sans-serif; font-size:1.25em;">Back to top</span></div>

<section class="footer-section">
<ul>
    <li><a href="faq.html">FAQ</a></li>
    <li><a href="terms-of-use.html">TERMS</a></li>
    <li><a href="usage-rights.html" style="color:#ff6000; text-decoration:underline;">USAGE RIGHTS</a></li>
    <li><a href="privacy-policy.html">PRIVACY POLICY</a></li>
    <li><a href="contact.html">CONTACT</a></li>
    <li><a href="the-editors.html">MEET THE STAFF</a></li>
</ul>

<h3 class="subscribe-footer"><a href="subscribe.html">Subscribe to our newsletter</a></h3>
<div id="social-links-container">
<ul class="social" style="height:40px;">
<li><a href="https://twitter.com/3ElementsReview" title="Follow @3ElementsReview" target="_blank"><img src="images/twitter.svg" width="25%" alt="If you like our literary journal, follow 3Elements Review on Twitter" border="none"></a></li>
<li><a href="https://www.facebook.com/pages/3Elements-Review/165239120323115" title="Like us on Facebook" target="_blank"><img src="images/facebook.svg" width="25%" alt="If you find our literary journal interesting, like 3Elements Review on Facebook" border="none"></a></li>
<li><a href="https://plus.google.com/102175306984563852786" rel="publisher" title="+1 our page on Google+" target="_blank"><img src="images/google-plus.svg" width="25%" alt="Recommend our literary journal 3Elements Review on Google+" border="none"></a></li>
<li><a href="http://www.stumbleupon.com/stumbler/3elementsreview" title="Come say hello!" target="_blank"><img src="images/stumble.svg" width="25%" alt="If you like our literary journal, you can find our 3Elements Review page on StumbleUpon" border="none"></a></li>
</ul>
</div><!---------------SOCIAL LINKS CONTAINER  END-------------------->

<h1 class="site-design">&nbsp;&nbsp;&nbsp;&copy;&nbsp;<script type="text/javascript">
    var dteNow = new Date();
    var intYear = dteNow.getFullYear();
    document.write(intYear);
</script> 3Elements Literary Review, Chicago, IL&nbsp;&nbsp;<a href="http://www.marlonfowler.com" target="_blank">Site design by Marlon Fowler</a></h1>

</section>
</footer>
</div><!------------------------CONTAINER THAT SURROUNDS ALL CONTENT BELOW THE NAVIGATION BAR  END------------------------------->


<!---------------------------------START OF GOOGLE RICH SNIPPETS DATA-------------------------------------------->
<div itemprop="location">
  <span itemscope itemtype="http://schema.org/Place">
    <div itemprop="geo">
      <span itemscope itemtype="http://schema.org/GeoCoordinates">
        <span property="latitude" content="41.943681"></span>
        <span property="longitude" content="87.640844"></span>
      </span>
    </div>
  </span>
</div>                 
<!---------------------------------END OF GOOGLE RICH SNIPPETS DATA-------------------------------------------->

</body>
</html>

CSS

@media only screen and (min-width:200px) and (max-width:767px) {
/******************************************NAVIGATION  START*********************************************/
h1.page-headline {
    top:0px;
    text-align:center;
    margin-top:0px;
    margin-bottom:0px;
    width:98%;
    font-size:1.5em;
}

h2.sub-head {
    top:10px;
    text-align:center;
    width:98%;
    font-size:1.15em;
    line-height:1.25em;
}

.mobile-nav-container {
    position:relative;
    background-color:#252525;
    top:-3px;
    width:100%;
    height:22px;
    border-bottom:3px solid #ffd09d;
    z-index:300;
    display:inline-block;
}

ul.nav-menu {/*navigation menu as a whole*/
    position:relative;
    top:-21px;
    margin:0px;
    padding:0px;
    background-color:#252525;
    width:100%;
    border-bottom: 2px solid #ff6000;
}

nav ul li a {/*navigation list items*/
    position:relative;
    top:0px;
    padding-left:5%;
    padding-right:5%;
    padding-top:3px;
    line-height:1.9em;
    border-bottom: 1px solid #313131;
    width:90%;
    height:30px;
    display:inline-block;
    font-family:myriad pro;
    font-size:1em;
    list-style:none;
    transition:300ms;
    -webkit-transition:300ms;
}

nav ul li {/*drop down list padding settings*/
    list-style:none;
}

nav li a {/*main navigation text color and padding settings*/
    position:relative;
    top:0px;
    margin:0px;
    padding:0px;
    color:#ffd09d;
    text-decoration:none;
}

.nav-menu li:active a {/*main navigation TEXT HOVER effects*/
    color:#ff6000;
    background-color:#beb29a;
    transition:400ms;
    -webkit-transition:400ms;
}

.nav-menu li:hover a {/*main navigation TEXT HOVER effects*/
    color:#ffa84a;
    transition:300ms;
    -webkit-transition:300ms;
}

.home-btn-mobile {
    position:relative;
    margin:0px;
    top:-20px;
    left:65px;
    outline:none;
    list-style:none;
    display:inline-block;
}

button.open-menu-small {
    position:relative;
    top:1px;
    left:3%;
    margin:0px;
    padding:0px;
    width:23px;
    height:19px;
    display:inline-block;
    outline:none;
    background-color:#353535;
    border:2px solid #424242;
    box-shadow:0px 0px 2px #000;
    cursor:pointer;
}

button.open-menu-small:active {
    cursor:pointer;
    border:2px solid #353535;
    box-shadow:none;
}
/******************************************NAVIGATION  END*********************************************/

/******************************************CONTENT FOR ALL PAGES*********************************************/
#container {
    position:relative;
    top:-15px;
    height:300px;
}

#main-image img {
    position:relative;
    top:0px;
    width:100%;
    height:auto;
    margin:0px;
    padding:0px;
}

#main-image2 {
    position:relative;
    top:0px;
    width:100%;
    height:37px;
    margin:0px;
    padding:0px;
}

#main-logo-mobile {
    position:absolute;
    top:1px;
    left:43%;
    width:32px;
    background-repeat:no-repeat;
    z-index:1000;
    border:none;
    outline:none;
    display:block;
}

.image-sub-head {
    position:absolute;
    top:43px;
    left:0px;
    right:0px;
    text-align:center;
    font-family:myriad pro light, arial, sans-serif;
    font-size:1.3em;
    color:#ffffff;
    opacity:1;
    z-index:4;
}

.current-elements {
    top:30px;
    width:100%;
    left:0px;
    right:0px;
    text-align:center;
    font-size:1.65em;
    line-height:.85em;
    opacity:1;
}

#elements-ticker {
    top:15px;
    left:0px;
    width:100%;
    margin-left:auto;
    margin-right:auto;
    padding-bottom:5px;
}
/******************************************CONTENT FOR ALL PAGES  END*********************************************/

/*****************************************USAGE RIGHTS**************************************************/
p.usage-rights {
    top:20px;
    width:95%;
    left:1%;
    font-size:1em;
    text-align:left;
    line-height:1.5em;
}

.p-social:visited, .p-social:link {
    color:#ff6000;
    text-decoration:none;

}

.p-social:hover {
    color:#ff6000;
    text-decoration:underline;

}
/*****************************************USAGE RIGHTS  END**************************************************/

/*****************************************FOOTER**************************************************/
footer.bottom-footer {
    position:absolute;
    width:100%;
    height:200px;
    background-color:#111111;
    padding-right:0px;
}

section.footer-section ul {
    position:relative;
    width:100%;
    height:120px;
    margin:0px!important;
    padding:0px!important;
    text-align:center;
}

section.footer-section li {/*footer navigation text*/
    top:20px;
    left:0px;
    margin-left:auto;
    margin-right:auto;
    font-size:.8em;
    text-decoration:none;
    -webkit-transition:.5s ease-in-out;
    -moz-transition:.5s ease-in-out;
    -ms-transition:.5s ease-in-out;
    -o-transition:.5s ease-in-out;
    transition:.5s ease-in-out;
    border-left:1px solid #ff6000;
    border-right:1px solid #ff6000;
    padding-left:7px;
    padding-right:5px;
    display:inline;
}

section.footer-section li a {
    color:#f8f4ec;
    text-decoration:none;
}

section.footer-section li:nth-child(1), section.footer-section li:nth-child(2), section.footer-section li:nth-child(3), section.footer-section li:nth-child(4), section.footer-section li:nth-child(5) {
    border-right:none;
}

section.footer-section li a:hover {/*footer navigation text hover effects*/
    color:#ffd09d;
    text-decoration:underline;
    -webkit-transition:.4s ease-in-out;
    -moz-transition:.4s ease-in-out;
    -ms-transition:.4s ease-in-out;
    -o-transition:.4s ease-in-out;
    transition:.4s ease-in-out;
    -webkit-appearance:
}

#social-links-container {
    top:-20px;
    left:8px;
    width:120px;
    height:38px;
    margin-left:auto;
    margin-right:auto;
    z-index:1000!important;
}

ul.social li {
    top:0px!important;
    width:100%;
    height:50px;
    margin-left:-16.5px!important;
    list-style-type:none;
    display:inline;
    left:0px!important;
    z-index:1000!important;
    transition:30ms;
    -webkit-transition:30ms;
    border:none!important;

}

ul.social li:hover {
    top:5px!important;
    transition:30ms;
    -webkit-transition:30ms;
    -webkit-filter:sepia(0%)!important;
    filter:sepia(0%)!important;
}

ul.social li a {
    outline:none;
    border:none;
}

h1.site-design {
    top:0px;
    left:0px;
    margin-bottom:0px;
    text-align:center;
    margin-left:auto;
    margin-right:auto;
    width:95%;
    padding-bottom:0px;
    font-size:.7em;
}

h1.site-design a:visited {
    color:#ff6000;      
}

h3.subscribe-footer {
    position:absolute;
    top:65px;
    left:0px;
    margin:0px!important;
    padding-bottom:0px!important;
    width:100%;
    text-align:center;
    font-size:.9em;
}

#nav-arrow {
    top:95px;
    width:70px;
    height:30px;
    right:2px;
    z-index:2;
    text-align:center;
}

#nav-arrow:hover {
    cursor:pointer;
}

span.arrow-text {
    position:relative;
    top:-7px;
    font-size:.75em!important;
}
/*****************************************FOOTER  END**************************************************/

/*****************************************MAIN LAYOUT ITEMS THAT SHOULD NOT BE     DISPLAYED IN MOBILE VIEW**************************************************/
nav.container, nav.container ul, nav.container-home, nav.container-home ul {
    display:none;
}

.current, .submit, .guidelines, .blog, .past, .about {
    display:none;
}

.image-sub-head-home {
    display:none;
}

#main-logo {
    display:none;
}

.image-header {
    display:none;
}
Теги:

2 ответа

0
Лучший ответ

У меня есть простой хак для вас

$(window).scroll(function()
{
    if( $(window).scrollTop() > 36 )
    {
    $('.mobile-nav-container').css({position: 'fixed'});
        $('#container').css({
            marginTop: '400px'
        });
    } 
    else 
    {
        $('.mobile-nav-container').css({position: 'relative', top: '-3px'});
        $('#container').css({
            marginTop: '0px'
        });
    }
});

Вы можете протестировать его здесь: http://jsfiddle.net/nXPHZ/

Чтобы сделать его более подходящим, я рассчитал высоту меню в JS и передал его в вызов css().

  • 0
    Спасибо, отлично работает.
0

Проблема заключается в том, что nav является posiiton:relative он находится в потоке документа, и высота определяет верхнее содержание контента. Как только это position:fixed оно удаляется из потока документов, и поэтому содержимое не смещается на него.

Предложите вам обернуть содержимое в контейнер и установить соответствующий запас

Ещё вопросы

Сообщество Overcoder
Наверх
Меню