CSS: stała pozycja na osi X, ale nie y?


104

Czy istnieje sposób na ustalenie pozycji tylko na osi X? Więc kiedy użytkownik przewinie w górę, znacznik DIV będzie przewijał się razem z nim, ale nie na boki?


3
Czy jest OK, gdybym podał rozwiązanie tego problemu w JS?
Starx,

1
Aby to zrobić, potrzebujesz javascript.
LostLin

@Starx - nie tylko jest OK, to jest wymagane :-)
Pete Wilson,

Niedawno odpowiedziałem na podobne pytanie, które może być bardziej podobne do tego, czego szukasz: stackoverflow.com/questions/8673560/ ...
Wex

Wiem, że to dość stare pytanie, ale czy nadal masz problemy z tym pytaniem?
Starx

Odpowiedzi:


58

Jest to również prosta technika wykorzystująca skrypt. Możesz tutaj również sprawdzić demo .

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;
}

Zaktualizuj kredyt: @ PierredeLESPINAY

Jak skomentowano, aby skrypt obsługiwał zmiany w css bez konieczności ich ponownego kodowania w skrypcie. Możesz użyć następujących.

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

Demo :)


@PeteWilson, Ok, sprawdź to rozwiązanie
Starx

2
Co myślisz o uzyskaniu leftwartości na początku funkcji, takiej jak init_left = $('#header').position()['left']lub coś podobnego?
Pierre de LESPINAY

@PierredeLESPINAY, Tak, bardzo dobra uwaga. To uczyniłoby go wystarczająco elastycznym, aby wspierać zmiany.
Starx

2
Uwielbiam to rozwiązanie i sam z niego korzystałem. Jednym z problemów, które mam z tym, jest to, że odświeżanie jest trochę przerywane, gdy robisz płynne przewijanie (np. Przeciągając pasek przewijania). Wygląda na to, że odświeżanie javascript jest wolniejsze niż odświeżanie css. Jakieś rozwiązanie?
jsarma


12

Jeśli twój blok jest pierwotnie ustawiony jako statyczny, możesz spróbować tego

$(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>


8

Nie, nie jest to możliwe w przypadku czystego CSS. Ten rodzaj pozycjonowania naprawia element w rzutni. Proponuję po prostu przymocować element do jednej ze stron widoku (tj. Do góry, dołu, lewej lub prawej), aby nie kolidował z inną zawartością.


7

Teraz, gdy urządzenia mobilne stanowią ponad 70% rynku internetowego, możesz stworzyć coś inteligentnego i elastycznego, aby to zrobić.

Możesz to bardzo łatwo stworzyć za pomocą samego css, użyj overflow-x: scroll dla kontenera i overflow-y: scroll dla innego kontenera. W prosty sposób można ustawić elementy kontenera o szerokości: 100vw i wysokości: 100vh.

Kliknij środkowym przyciskiem myszy przykład, aby go przetestować. Działa najlepiej na urządzeniach mobilnych, ponieważ nie widać pasków przewijania.

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>


Nie podoba mi się, że dolny pasek przewijania jest widoczny tylko podczas przewijania do stopy ...
Fanky

W przeglądarce mobilnej nie pojawi się. W Chrome możesz to ukryć za pomocą tego CSS .yourclass::-webkit-scrollbar-track, .yourclass::-webkit-scrollbar-thumb {display:none;}. W przeglądarce Firefox możesz go ukryć, umieszczając go poza overflow:hiddenpojemnikiem. Ale to kolejne pytanie, na które udzielono już wcześniej odpowiedzi, jestem tego pewien.
EPurpl3

2

Rozwiązanie Starx było dla mnie niezwykle pomocne. Ale miałem pewne problemy, gdy próbowałem zaimplementować z nim pasek boczny przewijania w pionie. Oto mój początkowy kod, oparty na tym, co napisał Starx:

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

Trochę różni się od rozwiązania Starx, ponieważ myślę, że jego kod został zaprojektowany tak, aby umożliwić menu unoszenie się w poziomie zamiast w pionie. Ale to tylko na bok. Problem, który miałem z powyższym kodem, polega na tym, że w wielu przeglądarkach lub w zależności od obciążenia komputera ruchy menu byłyby nierówne, podczas gdy początkowe rozwiązanie css było ładne i płynne. Przypisuję to tym, że przeglądarki wolniej uruchamiają zdarzenia javascript niż implementują css.

Moim alternatywnym rozwiązaniem tego problemu z niestabilnością jest ustawienie ramy na stałe zamiast bezwzględne, a następnie wyeliminowanie ruchów poziomych metodą starx.

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

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

Możesz powiedzieć, że wszystko, co robię, to zamiana niestabilności przewijania w pionie na niestabilność przewijania w poziomie. Ale chodzi o to, że 99% przewijania jest w pionie i jest znacznie bardziej irytujące, gdy jest niestabilne niż w przypadku przewijania w poziomie.

Oto mój pokrewny post w tej sprawie, jeśli jeszcze nie wyczerpałem cierpliwości wszystkich: Naprawianie menu w jednym kierunku w jquery


2

Natknąłem się na ten post, szukając fajnego sposobu, aby mój nagłówek / pasek nawigacyjny był wyśrodkowany i reagował na zmiany rozmiaru.

//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)
  }
})

Podczas przewijania pasek przesuwa się w górę z ekranu. Jeśli przewiniesz w lewo / w prawo, pozostanie na stałe.


Dzięki bracie. To zadziałało. Ale takie proste !! Genius you
Ram

0

Zdaję sobie sprawę, że ten wątek jest bardzo stary, ale pomógł mi znaleźć rozwiązanie dla mojego projektu.

W moim przypadku miałem nagłówek, który nigdy nie chciał mieć mniej niż 1000 pikseli szerokości, nagłówek zawsze na górze, z treścią, która mogłaby być nieograniczona w prawo.

header{position:fixed; min-width:1024px;}
<header data-min-width="1024"></header>

    $(window).on('scroll resize', function () {
        var header = $('header');
        if ($(this).width() < header.data('min-width')) {
            header.css('left', -$(this).scrollLeft());
        } else {
            header.css('left', '');
        }
    });

Powinno to również obsługiwać, gdy Twoja przeglądarka jest mniejsza niż minimalna szerokość nagłówków


0

Dodałem tylko pozycję: absolutną i to rozwiązało mój problem.


8
Bezwzględne pozycjonowanie ustala elementy względem dokumentu. Stałe pozycjonowanie naprawia je względem okna. Jeśli użycie absolutnego rozwiązało twój problem, to nie miałeś tego samego problemu, co to pytanie.
Niall,

0

To bardzo stary wątek, ale znalazłem rozwiązanie tego problemu w czystym CSS, używając kreatywnego zagnieżdżania. W ogóle nie byłem fanem metody jQuery ...

Fiddle tutaj: https://jsfiddle.net/4jeuv5jq/

<div id="wrapper">
    <div id="fixeditem">
        Haha, I am a header. Nah.. Nah na na na
    </div>
    <div id="contentwrapper">
        <div id="content">
            Lorem ipsum.....
        </div>
    </div>
</div>

#wrapper {
position: relative;
width: 100%;
overflow: scroll;
}

#fixeditem {
position: absolute;
}

#contentwrapper {
width: 100%;
overflow: scroll;
}

#content {
width: 1000px;
height: 2000px;
}

6
Twoje rozwiązanie wymaga przewijania elementu div kontenera zawartości zamiast rzeczywistego okna, co jest dalekie od ideału - twoje skrzypce pokazują, dlaczego. Treść spływa z prawej strony strony, ale poziomego paska przewijania nie ma na ekranie. To duży problem z użytecznością.
Niall,

0

Zaktualizowano skrypt, aby sprawdzić pozycję początkową:

function float_horizontal_scroll(id) {
var el = jQuery(id);
var isLeft = el.css('left') !== 'auto';
var start =((isLeft ? el.css('left') : el.css('right')).replace("px", ""));
jQuery(window).scroll(function () {
    var leftScroll = jQuery(this).scrollLeft();
    if (isLeft)
        el.css({ 'left': (start + leftScroll) + 'px' });
    else
        el.css({ 'right': (start - leftScroll) + 'px' });
});

}



0

Na div rodzic możesz dodać

overflow-y: scroll; 
overflow-x: hidden;

0
$(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
    });
});

Dzięki


0

Tak, faktycznie możesz to zrobić tylko za pomocą CSS ...

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

Powiedz mi, czy to działa


-1

Bardzo prostym rozwiązaniem jest:

window.onscroll = function (){
  document.getElementById('header').style.left= 15 - (document.documentElement.scrollLeft + document.body.scrollLeft)+"px";
}

powinieneś position:fixeddo tego użyć CSS3, zamiast korzystać z rozwiązania js
Muhammad Omer Aslam

-3

Wygląda na to, że musisz użyć pozycji: ustalona, ​​a następnie ustaw górną pozycję na wartość procentową, a lewą lub prawą pozycję na stałą jednostkę.

Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.