Элементы, которые будут вырезаны при достижении области Navbar с помощью прокрутки - PullRequest
0 голосов
/ 10 февраля 2020

надеюсь, кто-нибудь может помочь мне с этим. У меня есть фиксированная панель навигации без цвета фона и заданной высоты c. Теперь при прокрутке вверх / вниз я хочу, чтобы элементы обрезались на границе навигационной панели (отмечены красным на примере графика c), чтобы они не отображались в области навигационной панели. Есть ли Javascript решение для этого?

Вот пример графика c, как он должен себя вести. before scrolling when cutting elements at navbar border

Спасибо за любую подсказку.

Обновление: после подсказки Хидзики Мизукузы мой окончательный код для этого решения выглядит следующим образом ...

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

html {
  background: url("Background.jpg") no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

nav {
  height: 50px;
  position: fixed;
  top: 0;
  width: 100%;
  display: flex;
  align-items: center;
}

a {
  text-decoration: none;
  color: black;
}

nav div {
  background-color: yellow;
  margin: 0 20px;
  padding: 5px;
}

img {
  height: 300px;
}

section {
  display: flex;
}

#content {
  position:fixed;
  top: 50px;
  overflow: scroll;
  height: calc(100% - 50px);
}

::-webkit-scrollbar {
  width: 0px;
  background: transparent; /* make scrollbar transparent */
}
<body>

  <nav>
    <div><a href="#About">About</a></div>
    <div><a href="#Products">Products</a></div>
    <div><a href="#Shop">Shop</a></div>
    <div><a href="#Carrer">Carrer</a></div>
  </nav>

  <div id="content">
    <section>
      <div>
        <img src="Cat.jpg" alt="Cat">
      </div>
      <div>
        What is Lorem Ipsum?
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

        Why do we use it?
        It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

        Where can I get some?
        There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
      </div>
    </section>
    <section>
      <div>
        <img src="Cat.jpg" alt="Cat">
      </div>
      <div>
        What is Lorem Ipsum?
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

        Why do we use it?
        It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

        Where can I get some?
        There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
      </div>
    </section>
    <section>
      <div>
        <img src="Cat.jpg" alt="Cat">
      </div>
      <div>
        What is Lorem Ipsum?
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

        Why do we use it?
        It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

        Where can I get some?
        There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
      </div>
    </section>
  </div>
    

</body>

С помощью :: - webkit-scrollbar Мне также удалось скрыть полосу прокрутки.

Ответы [ 5 ]

2 голосов
/ 10 февраля 2020

Javascript не требуется, и я думаю, что CSS решение является более предпочтительным.

Если ваша высота панели навигации не будет меняться во время работы страницы, вы можете просто установить фиксированную позицию контента и иметь высоту калибровки. c (100% - высота панели навигации), вершина - высота панели навигации.

Допустим, высота вашего панели навигации составляет 50 пикселей:

#navbar, #content{
  position:fixed;
  left: 0;
  background: transparent;
}

#navbar{
  top: 0;
  height: 50px;
  list-style-type: none;
}

#content{
  top: 50px;
  height: calc(100% - 50px);
  overflow: auto;
}

#body{
  position: absolute;
  width: 100%;
  height: 100%;
  margin: 0;
  top: 0;
  left: 0;
  background: linear-gradient(45deg, grey, black); 
}

#navbar>li{
  display: inline-block;
  background: yellow;
  margin: 0 15px;
}
<div id="body">
  <ul id="navbar">
     <li>About</li>  
     <li>Products</li> 
     <li>Shop</li> 
     <li>Career</li> 
  </ul>
  <div id="content">
    <p>What is Lorem Ipsum?
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

        Why do we use it?
        It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).


        Where does it come from?
        Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

        The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

        Where can I get some?
        There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
    </p>
  </div>
</div>

Если вы не уверены в высоте панели навигации, вы можете использовать гибкий макет.

#body{
  position: fixed;
  width: 100%;
  height: 100%;
  margin: 0;
  top: 0;
  left: 0;
  background: linear-gradient(45deg, grey, black); 
  display:flex;
  flex-direction: column;
}

#navbar, #content{
  background: transparent;
}

#navbar{
  list-style-type: none;
}

#content{
  flex-grow: 1;
  overflow: auto;
}



#navbar>li{
  display: inline-block;
  background: yellow;
  margin: 0 15px;
}
<div id="body">
  <ul id="navbar">
     <li>About</li>  
     <li>Products</li> 
     <li>Shop</li> 
     <li>Career</li> 
  </ul>
  <div id="content">
    <p>What is Lorem Ipsum?
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

        Why do we use it?
        It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).


        Where does it come from?
        Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

        The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

        Where can I get some?
        There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
    </p>
  </div>
</div>
0 голосов
/ 10 февраля 2020

Итак, чтобы достичь того, что вы хотите с чистым CSS, вам нужно сделать несколько «хаков», я сделал небольшую демонстрацию, которая показывает, как чего-то подобного можно достичь.

  1. Создание липкой навигации;
  2. Создание элемента с тем же фоновым изображением, что и у тела внутри (с той же высотой, что и у изображения);
  3. Создание навигации с переполнением-скрытым;
  4. Поместите изображение вверху страницы.

Взгляните на демонстрацию:

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

body{
  height: 200vh;
}

nav{
  position: sticky;
  top: 0;
  height: 30px;
  overflow-y: hidden;
  width: 100vw;
}

ul{
  list-style: none;
  display: flex;
  justify-content: space-around;
  color: red;
  font-weight: bold;
  font-size: 20px;
  background-image: url("https://p.bigstockphoto.com/eIdTXLbqQilMs9xbjvcs_bigstock-Aerial-View-Of-Sandy-Beach-Wit-256330393.jpg");
  background-size: 100vw 100vh;
  background-repeat: no-repeat;
  height: 100vh;
  width: 100%;
}

img{
  height: 100vh;
  width: 100vw;
  position: absolute;
  top: 0;
  z-index: -1;
}
<nav>
    <ul>
        <li>Home</li>
        <li>About</li>
        <li>Section</li>
    </ul>
</nav>

<main>
    <img src="https://p.bigstockphoto.com/eIdTXLbqQilMs9xbjvcs_bigstock-Aerial-View-Of-Sandy-Beach-Wit-256330393.jpg" alt="">
</main>
0 голосов
/ 10 февраля 2020

Проблема заключается в том, что элементы панели навигации фиксируются так, как они принадлежат панели навигации, поэтому прокрутка не влияет на них.

Простой способ решить эту проблему - не исправить панель навигации и вместо этого добавить фиксированную красную ссылку для имитации границы этой панели навигации. Это позволило бы этим элементам уйти на прокрутке go, но сохранить эту красную линию деления на своем месте.

Надеюсь, это помогло: D

0 голосов
/ 10 февраля 2020

Нет необходимости в javascript. Вы можете просто добавить тот же фон, что и страница, к элементу nav с помощью css.

Создать что-то вроде <div class="background-container"></div> в панели навигации, масштабировать его до области просмотра поэтому фон идентичен фону самой страницы, а затем скрыть лишнюю часть, установив overflow: hidden на панели навигации.

0 голосов
/ 10 февраля 2020

Вам не нужно javascript, вы можете добавить

position: sticky;
top: 0;

В CSS (на панели навигации)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...