CSS: фиксированная позиция по оси х, но не у? - PullRequest
97 голосов
/ 12 января 2010

Есть ли способ зафиксировать положение только на оси х? Поэтому, когда пользователь прокручивает вверх, тег div будет прокручиваться вместе с ним, но не из стороны в сторону?

Ответы [ 17 ]

56 голосов
/ 30 декабря 2011

Это простая техника с использованием сценария также.Вы можете посмотреть демо здесь .

JQuery

$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});

CSS

#header {
    top: 15px;
    left: 15px;
    position: absolute;
}

Обновление Кредит: @ PierredeLESPINAY

Как прокомментировано, чтобы скрипт поддерживал изменения в CSS без необходимости перекодировать их в скрипте.Вы можете использовать следующее.

var leftOffset = parseInt($("#header").css('left')); //Grab the left position left first
$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + leftOffset //Use it later
    });
});

Демо :)

13 голосов
/ 09 августа 2017

Это старая ветка, но у CSS3 есть решение.

position: sticky;

Посмотрите этот пост в блоге.

Демонстрация:

css position sticky animation

И эта документация.

10 голосов
/ 10 октября 2016

Если ваш блок изначально позиционируется как статический, вы можете попробовать это

$(window).on('scroll', function () {

  var $w = $(window);
  $('.position-fixed-x').css('left', $w.scrollLeft());
  $('.position-fixed-y').css('top', $w.scrollTop());

});
.container {
  width: 1000px;
}

.position-fixed-x {
  position: relative; 
}

.position-fixed-y {
  position: relative;
}

.blue-box {
  background:blue;
  width: 50px;
  height: 50px;
}

.red-box {
  background: red;
  width: 50px;
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

<div class="position-fixed-y red-box">
  
</div>

The pattern of base pairs in the DNA double helix encodes the instructions for building the proteins necessary to construct an entire organism. DNA, or deoxyribonucleic acid, is found within most cells of an organism, and most organisms have their own unique DNA code. One exception to this is cloned organisms, which have the same exact DNA code as their parents do.

<div class="position-fixed-x blue-box">
  
</div>

DNA strands are composed of millions of sub-units, called nucleotides. Each nucleotide contains a 5-carbon sugar, a phosphate group and a nitrogen base. There are four different variations of the nitrogen base group, responsible for all of the variation between two different DNA strands. The four different variations are called adenine, guanine, cytosine and thymine, but they are typically abbreviated and only referred to by their first letter. The sequence of these different nitrogen bases makes up the code of the DNA.

The DNA strand splits in two, and forms two different DNA strands during cell replication. However, sometimes this process is not perfect, and mistakes occur. These mistakes may change the way an organism is constructed or functions. When this happens, it is called a mutation. These mutations can be helpful or harmful, and they are usually passed on to the organism’s offspring.
  
 The traits of a living thing depend on the complex mixture of interacting components inside it. Proteins do much of the chemical work inside cells, so they largely determine what those traits are. But those proteins owe their existence to the DNA (deoxyribonucleic acid), so that is where we must look for the answer.
The easiest way to understand how DNA is organized is to start with its basic building blocks. DNA consists of four different sugars that interact with each other in specific ways. These four sugars are called nucleotide bases and have the names adenine (A), thymine (T), cytosine (C) and guanine (G). Think of these four bases as letters in an alphabet, the alphabet of life!
If we hook up these nucleotides into a sequence--for example, GATCATCCG--we now have a little piece of DNA, or a very short word. A much longer piece of DNA can therefore be the equivalent of different words connected to make a sentence, or gene, that describes how to build a protein. And a still longer piece of DNA could contain information about when that protein should be made. All the DNA in a cell gives us enough words and sentences to serve as a master description or blueprint for a human (or an animal, a plant, or a microorganism).
Of course, the details are a little more complicated than that! In practice, active stretches of DNA must be copied as a similar message molecule called RNA. The words in the RNA then need to be "read" to produce the proteins, which are themselves stretches of words made up of a different alphabet, the amino acid alphabet. Nobel laureates Linus Pauling, who discerned the structure of proteins, and James Watson and Francis Crick, who later deciphered the helical structure of DNA, helped us to understand this "Central Dogma" of heredity--that the DNA code turns into an RNA message that has the ability to organize 20 amino acids into a complex protein: DNA -> RNA -> Protein.
To understand how this all comes together, consider the trait for blue eyes. DNA for a blue-eyes gene is copied as a blue-eyes RNA message. That message is then translated into the blue protein pigments found in the cells of the eye. For every trait we have--eye color, skin color and so on--there is a gene or group of genes that controls the trait by producing first the message and then the protein. Sperm cells and eggs cells are specialized to carry DNA in such a way that, at fertilization, a new individual with traits from both its mother and father is created.
</div>
9 голосов
/ 12 января 2010

Нет, это невозможно с чистым CSS. Такой тип позиционирования фиксирует элемент в окне просмотра. Я бы предложил просто прикрепить элемент к одной из сторон области просмотра (то есть сверху, снизу, слева или справа), чтобы он не мешал другому содержимому.

5 голосов
/ 24 августа 2018

Теперь, когда мобильная связь составляет более 70% от интернет-рынка, вы можете создать что-то умное и гибкое для этого.

Вы можете создать это очень просто, используя только css, используя overflow-x: scroll для контейнера и overflow-y: scroll для другого контейнера. Вы можете легко расположить элементы контейнера с шириной: 100vw и высотой: 100vh.

Средний клик по примеру, чтобы проверить его. Лучше всего работает на мобильных устройствах, потому что вы не видите полос прокрутки.

body{max-width:100%}
*{box-sizing:border-box;}
.container{background:#ddd;overflow-y:scroll;width:500px;max-height:100vh;}
.header{background: pink;}
.body{background: teal;padding:20px;min-width: 100%;overflow:scroll;overflow-y:hidden;min-height:300px;}
.body >div{min-width:800px;}
<body>
  <div class="container">
    <div class="header">
       Button 1 > Button 2 > Button 3
    </div>
    <div class="body">
      <div>
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
<br><br>
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
<br><br>
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<br><br>
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<br><br>
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<br><br>
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<br><br>
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<br><br>
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>
    </div>
  </div>
</body>
2 голосов
/ 27 апреля 2013

Решение Starx было чрезвычайно полезным для меня. Но у меня были некоторые проблемы, когда я пытался внедрить в него боковую панель с вертикальной прокруткой. Вот мой исходный код, основанный на том, что написал Старкс:

function fix_vertical_scroll(id) {
    $(window).scroll(function(){
        $(id).css({
            'top': $(this).scrollTop() //Use it later
        });
    });
}

Это немного отличается от решения Starx, потому что я думаю, что его код предназначен для того, чтобы меню могло перемещаться горизонтально, а не вертикально. Но это только в сторону. Проблема, с которой я столкнулся в приведенном выше коде, заключается в том, что во многих браузерах или в зависимости от загрузки ресурсов компьютера движения меню будут прерывистыми, тогда как первоначальное решение css было приятным и плавным. Я приписываю это браузерам, которые медленнее запускают события JavaScript, чем при реализации CSS.

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

function float_horizontal_scroll(id) {
    jQuery(window).scroll(function(){
        jQuery(id).css({
            'left': 0 - jQuery(this).scrollLeft()
        });
    });
}

#leftframe {
 position:fixed;
 width: 200;
}   

Вы могли бы сказать, что все, что я делаю, - это обмен вертикальной прокрутки на горизонтальную прокрутку. Но дело в том, что 99% прокрутки - вертикальная, и это намного раздражает, когда это изменчиво, чем когда горизонтальная прокрутка.

Вот мой связанный пост по этому вопросу, если я еще не исчерпал всеобщее терпение: Исправление меню в одном направлении в jquery

1 голос
/ 06 апреля 2018

Я наткнулся на этот пост в поисках хорошего способа держать мой заголовок / панель навигации в центре и реагировать на изменения размера.

//CSS
.nav-container {
  height: 60px;  /*The static height*/
  width: 100%;  /*Makes it responsive to resizing the browser*/
  position: fixed;  /*So that it will always be in the center*/
}

//jQuery
$(window).scroll(() => {
  if ($(document).scrollTop() < 60) {
    $('.nav-container').css('top', $(document).scrollTop() * -1)
  }
})

При прокрутке полоса перемещается вверх за пределы экрана. Если вы прокрутите влево / вправо, он останется фиксированным.

0 голосов
/ 19 февраля 2018

Да, вы можете сделать это только с помощью CSS ...

body { width:100%; margin-right: 0; margin-left:0; padding-right:0; padding-left:0; }

Подскажите, работает ли он

0 голосов
/ 26 ноября 2017

Очень простое решение:

window.onscroll = function (){
  document.getElementById('header').style.left= 15 - (document.documentElement.scrollLeft + document.body.scrollLeft)+"px";
}
0 голосов
/ 18 сентября 2017
$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});

Спасибо

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