2017-01-17 3 views
-1

Как следует из названия, у меня есть все основания создать веб-страницу с большим логотипом над панелью навигации. Эта панель навигации будет перемещаться вверх по мере прокрутки страницы до тех пор, пока она не встанет на место в верхней части экрана. Затем я хотел бы, чтобы меньший логотип появлялся под панелью навигации и оставался запертым на месте. Я искал четыре дня для решения на этой веб-странице и в других местах, которые не имеют преимущественной силы. Чаще всего это решение включает загрузку jquery-библиотек или загрузочных библиотек. Я не хотел бы использовать это, если это возможно. Причина этого заключается в том, что я создаю эту веб-страницу в качестве учебного опыта, а код, хранящийся в других местах, не содержит частей, которые будут путать меня в это время. Поэтому в основном я хочу знать, как это работает, и не получить простой метод копирования-вставки, который имеет библиотеку, выполняющую всю работу.Создание липкой панели навигации под логотипом без использования внешних библиотек

Вот что я thusfar, и это было полностью основано на этом примере: http://codepen.io/Guilh/pen/JLKbn

HTML:

 <!DOCTYPE html> 
<html lang="en"> 
    <head> 
    <meta charset="utf-8"> 
    <title>The Den</title> 
    <link rel="stylesheet" href="style.css"> 
    <script src="script.js"></script> 
    </head> 
    <body> 
<header> 
    <table bordercolor="FD0000" align="center" cellspacing="0" cellpadding="0" style="border-color: FD0000; border-width:2px; border-top-style:solid; border-right-style:solid; border-bottom-style:solid; border-left-style:solid;"> 
<tr><td><center><a href="http://www.wolvesofthedust.com/"><img src="http://i1288.photobucket.com/albums/b494/ShadowfangInnovia/WolvesoftheDustSiteHeader_zpsdddba823.png" height="auto" width="940" border="0" alt=" photo WolvesoftheDustSiteHeader_zpsdddba823.png"/></a> 
</center></td></tr></table> 
</header> 
<nav class="main-nav"> 
    <ul id="main-nav"> 
    <li><a href="#">Nav Link 1</a></li> 
    <li><a href="#">Nav Link 2</a></li> 
    <li><a href="#">Nav Link 3</a></li> 
    <li><a href="#">Nav Link 4</a></li> 
    </ul> 
</nav> 
<div class="main"> 
    <h2>Random words to fill in the gap.</h2> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 
    <p>Random words to fill in the gap.</p> 

</div> 
</body> 

CSS:

* { 
    box-sizing: border-box; 
} 
li { 
    float: left; 
} 
body { 
    margin: 0; 
    padding-top: 250px; 
} 
header { 
    height: 300px; 
    padding-top: 50px; 
    background: #f07057; 
} 
.main-nav, 
.main { 
    position: relative; 
} 
.main-nav { 
    background: #fff; 
    height: 80px; 
    z-index: 150; 
    margin-bottom: -80px; 
    box-shadow: 0 2px 3px rgba(0,0,0,.4); 
} 
header, 
.main-nav-scrolled { 
    position: fixed; 
    width: 100%; 
    top: 0; 
} 
.main { 
    background: #f2f2e8; 
    padding: 110px 50px 50px; 
    column-count: 2; 
    column-gap: 40px; 
    width: 100%; 
} 

JS:

var mn = $(".main-nav"); 
    mns = "main-nav-scrolled"; 
    hdr = $('header').height(); 

$(window).scroll(function() { 
    if($(this).scrollTop() > hdr) { 
    mn.addClass(mns); 
    } else { 
    mn.removeClass(mns); 
    } 
}); 

Проблема с приведенным выше примером заключается в том, что она работает только на странице codepen. В тот момент, когда я снимаю его с сайта и сохраняю его на документе блокнота ++ и открываю его, внезапно панель навигации прокручивается мимо намеченной точки и полностью закрывается. Это та же проблема, с которой я столкнулся с каждым другим учебником, с которым я столкнулся. Либо навигационная панель не может оставаться на экране, либо логотип станет фоном, который прокручивает текст, оставляя навигационную панель примерно на 3/4 до логотипа.

+0

Это поможет, если вы указали style.css и script.js. Также почему именно вы хотите избежать использования библиотек? Они действительно могут сделать такие вещи довольно тривиальными ... – Shadow

+0

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

ответ

0

Это без того, чтобы связать в другом месте.

$(function(){ 
 
    $(window).scroll(function() { 
 
     if ($(this).scrollTop() >= 290) { 
 
      $('nav.main-nav').addClass('stickytop'); 
 
     } 
 
     else { 
 
      $('nav.main-nav').removeClass('stickytop'); 
 
     } 
 
    }); 
 
});
body { 
 
    font:16px/1.5 'Raleway',Arial,sans-serif; 
 
    color:#fff; 
 
    margin:0; 
 
    padding:0 
 
} 
 
    
 
h1 { 
 
    font-size:50px; 
 
    font-weight:300; 
 
    text-align:center; 
 
    font-weight:700 
 
} 
 
    
 
span { 
 
    color:#27ae60; 
 
    font-weight:700 
 
} 
 
    
 
h2 { 
 
    font-size:35px; 
 
    text-align:left; 
 
    margin-left:-20px 
 
} 
 
    
 
nav.demo-nav { 
 
    width:350px; 
 
    margin:0 auto; 
 
    display:block 
 
} 
 
    
 
nav.demo-nav a { 
 
    font-size:19px; 
 
    display:inline-block; 
 
    text-align:center; 
 
    font-family:'Lato',sans-serif; 
 
    color:#27ae60; 
 
    font-weight:400; 
 
    padding:5px 15px; 
 
    text-transform:uppercase; 
 
    border-radius:2px; 
 
    letter-spacing:1px; 
 
    text-decoration:none; 
 
    margin-right:10px; 
 
    border:2px solid #ecf0f1; 
 
    border-radius:none 
 
} 
 
    
 
nav a.active,nav a:hover { 
 
    background:#ecf0f1; 
 
    color:#27ae60 
 
} 
 

 
header { 
 
    height:250px; 
 
    background:#2ecc71; 
 
    padding:23px 0 
 
} 
 
    
 
nav.main-nav { 
 
    background:#fff; 
 
    height:60px; 
 
    border-bottom:1px solid #dadada; 
 
    text-align: center; 
 
} 
 
    
 
nav.main-nav a { 
 
    font-family:'Lato',sans-serif; 
 
    font-size:20px; 
 
    text-decoration:none; 
 
    display:inline-block; 
 
    padding:15px 19px; 
 
    color:#27ae60; 
 
} 
 
    
 
.container { 
 
    display: inline; 
 
    margin:0 auto; 
 
} 
 

 
nav.main-nav.stickytop { 
 
    position:fixed; 
 
    top:0 
 
} 
 

 
.content { 
 
    color:#222; 
 
    padding:50px; 
 
    -webkit-column-count:3; 
 
/* Chrome, Safari, Opera */ 
 
    -moz-column-count:3; 
 
/* Firefox */ 
 
    column-count:3; 
 
    -webkit-column-gap:40; 
 
    column-gap:40px; 
 
} 
 
    
 
.content h2 { 
 
    margin:0; 
 
} 
 

 

 
@media all and (min-width: 360px) and (max-width: 480px) { 
 
    header { 
 
     padding:5px 0 55px; 
 
    } 
 
    
 
    nav.main-nav a { 
 
     font-size:17px; 
 
    } 
 
    
 
    nav.main-nav { 
 
     height:55px; 
 
    } 
 
    
 
    .container { 
 
     margin:0 auto; 
 
     width:50%; 
 
    
 
    } 
 
    
 
    .content { 
 
     -webkit-column-count:1; 
 
     /* Chrome, Safari, Opera */ 
 
     -moz-column-count:1; 
 
     /* Firefox */ 
 
     column-count:1; 
 
    } 
 
} 
 
    
 
@media screen and (max-width: 480px) { 
 
    header { 
 
     padding:5px 0 55px; 
 
    } 
 
    
 
    nav.main-nav a { 
 
     font-size:17px; 
 
    } 
 
    
 
    nav.main-nav { 
 
     height:55px; 
 
    } 
 
    
 
    .container { 
 
     width:92%; 
 
    } 
 
    
 
    .content { 
 
     -webkit-column-count:1; 
 
     /* Chrome, Safari, Opera */ 
 
     -moz-column-count:1; 
 
     /* Firefox */ 
 
     column-count:1 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<header> 
 
<h1>Creating <span>Sticky</span> Navigation</h1> 
 
<nav class="demo-nav"> 
 
     <a href="index.html" class="active">Using jQuery</a> 
 
     <a href="index2.html" >Using CSS</a> 
 
    </nav> 
 
</header> 
 
<nav class="main-nav"> 
 
<div class="container"> 
 
<a href="#">Home</a> 
 
    <a href="#">About</a> 
 
    <a href="#">Profile</a> 
 
    <a href="#">Contact</a> 
 
    </div> 
 
</nav> 
 
<div class="content"> 
 
<h2>Main Content Here!</h2> 
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum 
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum 
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum 
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum 
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum 
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum 
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum 
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum 
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum 
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum 
 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum 
 
</div>

+0

У меня недостаточно репутации, чтобы проголосовать, но этот ответ мне помог. Спасибо. – Shadowfang

0

Взгляните на эту статью CSS-трюками на эту тему; https://css-tricks.com/scroll-fix-content/ Это мой пример, когда я сделал это несколько раз сам.

Этот пример кода также отлично работает:

HTML:

<div class="wrap" id="wrap"> 

<header class="top-header"> 
    <span class="menu-icon">☰</span> 
    </header> 

    <div class="search"> 
    <input type="search" placeholder="Search or type URL" /> 
    </div> 

    <div class="top"> 
    <div class="hero"></div> 
    </div> 

    <main> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    </main> 

</div> 

CSS:

* { 
    box-sizing: border-box; 
} 
body { 
    margin: 0; 
} 

.wrap { 
    width: 320px; 
    border: 1px solid #ccc; 
    height: 480px; 
    overflow: auto; 
    position: relative; 
} 
.top-header { 
    position: fixed; 
    top: 0; 
    left: 0; 
    width: 320px; 
    height: 60px; 
    .menu-icon { 
    position: absolute; 
    top: 0; 
    right: 0; 
    padding: 18px 20px; 
    } 
    .fix-search & { 
    background: #eee; 
    } 
} 

.search { 
    position: absolute; 
    top: 155px; 
    left: 20px; 
    right: 20px; 
    input { 
    width: 265px; 
    border: 1px solid #ccc; 
    padding: 8px; 
    font-size: 15px; 
    transition: width 0.2s; 
    -webkit-appearance: none; 
    } 
    .fix-search & { 
    position: fixed; 
    top: 10px; 
    input { 
     width: 250px; 
    } 
    } 
} 

.top { 
    height: 250px; 
    padding-top: 40px; 
} 
.hero { 
    width: 200px; 
    height: 100px; 
    background: #ccc; 
    margin: 0 auto; 
} 

main { 
    padding: 0 20px; 
    display: flex; 
    flex-wrap: wrap; 
    justify-content: space-between; 
    div { 
    width: 125px; 
    height: 80px; 
    background: #ccc; 
    margin: 0 0 20px 0; 
    } 
} 

JavaScript:

var wrap = $("#wrap"); 

wrap.on("scroll", function(e) { 

    if (this.scrollTop > 147) { 
    wrap.addClass("fix-search"); 
    } else { 
    wrap.removeClass("fix-search"); 
    } 

}); 

https://codepen.io/chriscoyier/pen/AdaKr

+0

Это одна из многих ссылок, которые я уже посетил. То, что закончилось после добавления моего логотипа, состояло в том, что в любое время, когда я прокручивался достаточно далеко, панель поиска (замененная навигационной панелью) помещалась бы в мой логотип вместо того, чтобы логотип плавно прокручивался с экрана. Я заметил, что эта ссылка также указывает на использование JQuery, который я хотел бы использовать, если это возможно. Моя цель - построить это с базовым HTML, CSS и Javascript без каких-либо дополнительных библиотек. – Shadowfang

+0

Я только что проверил его еще раз. В тот момент, когда логотип добавляется, чтобы заменить значок заголовка в примере, код просто разваливается. Возможно, это участие таблицы с моим логотипом, поскольку у нее есть граница, построенная с использованием свойств таблицы. Несмотря на это, бар оказывается там, и логотип превращается в более фона, чем фактический заголовок. – Shadowfang

0

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <title>Bootstrap Example</title> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 
    <style> 
 
    .affix { 
 
     top: 0; 
 
     width: 100%; 
 
    } 
 
    .affix + .container-fluid { 
 
     padding-top: 70px; 
 
    } 
 
    </style> 
 
</head> 
 
<body> 
 

 
<header class="container-fluid" style="background-color:#F44336;color:#fff;height:200px;"> 
 
    <h1>Bootstrap Affix Example</h1> 
 
    <h3>Fixed (sticky) navbar on scroll, using jQuery</h3> 
 
    <p>Scroll this page to see how the navbar behaves.</p> 
 
    <p>The navbar is attached to the top of the page after you have scrolled passed the header element.</p> 
 
</header> 
 

 
<nav class="navbar navbar-inverse"> 
 
    <ul class="nav navbar-nav"> 
 
    <li class="active"><a href="#">Basic Topnav</a></li> 
 
    <li><a href="#">Page 1</a></li> 
 
    <li><a href="#">Page 2</a></li> 
 
    <li><a href="#">Page 3</a></li> 
 
    </ul> 
 
</nav> 
 

 
<div class="container-fluid" style="height:1000px"> 
 
    <h1>Some text to enable scrolling</h1> 
 
    <h1>Some text to enable scrolling</h1> 
 
    <h1>Some text to enable scrolling</h1> 
 
    <h1>Some text to enable scrolling</h1> 
 
    <h1>Some text to enable scrolling</h1> 
 
    <h1>Some text to enable scrolling</h1> 
 
    <h1>Some text to enable scrolling</h1> 
 
    <h1>Some text to enable scrolling</h1> 
 
    <h1>Some text to enable scrolling</h1> 
 
    <h1>Some text to enable scrolling</h1> 
 
    <h1>Some text to enable scrolling</h1> 
 
</div> 
 

 
<script> 
 
$(document).ready(function(){ 
 
    /* affix the navbar after scroll below header */ 
 
    $(".navbar").affix({offset: {top: $("header").outerHeight(true)} }); 
 
}); 
 
</script> 
 

 
</body> 
 
</html>

+0

Это делает трюк, однако есть ли способ сделать это без участия библиотек? Моя цель состоит в том, чтобы все мои HTML, CSS и JS принимали меня. Меня не особо волнует, если в процессе создания много javascript. Я просто хочу, чтобы этот процесс произошел без ссылки в другом месте. – Shadowfang

+0

@Shadowfang Я сделаю это –

+0

Не против ли вы взглянуть на отредактированный пост и посмотреть, что вы можете с ним сделать? Во втором примере, который вы опубликовали, также есть ссылка на JQuery в качестве источника сценария. Я прилагаю все усилия, чтобы избежать этого, как объяснялось выше. – Shadowfang

Смежные вопросы