2010-01-12 15 views
80

C'è un modo per fissare una posizione solo sull'asse x? Quindi, quando un utente scorre verso l'alto, il tag div scorrerà verso l'alto con esso, ma non da un lato all'altro?CSS: posizione fissa sull'asse x ma non y?

+3

Va bene, se ho dato una soluzione a questo problema JS? – Starx

+0

@Starx - non è solo OK, è necessario :-) –

+0

Recentemente ho risposto a una domanda simile che potrebbe essere più simile a quella che stai cercando: http://stackoverflow.com/questions/8673560/element -fixed-position-horizontally-static-vertical/8673659 # 8673659 – Wex

risposta

-3

Suoni come se fosse necessario utilizzare la posizione: fissa e quindi impostare la posizione superiore su una percentuale e la posizione sinistra o destra su un'unità fissa.

6

No, non è possibile con puro CSS. Questo tipo di posizionamento corregge l'elemento nella finestra. Suggerirei semplicemente di fissare l'elemento su uno dei lati del viewport (cioè superiore, inferiore, sinistro o destro) in modo che non interferisca con altri contenuti.

50

È una tecnica semplice che utilizza anche lo script. Puoi anche controllare una demo here.

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

Aggiornamento Credito: @PierredeLESPINAY

Come ha commentato, per rendere lo script sostenere i cambiamenti nel CSS senza doverli ricodificare nella sceneggiatura. È possibile utilizzare il seguente.

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 :)

+0

@PeteWilson, Ok controlla questa soluzione – Starx

+2

Cosa ne pensi di ottenere il valore 'left' all'inizio della funzione come' init_left = $ ('# header').position() ['left'] 'o qualcosa di simile? –

+0

@PierredeLESPINAY, Sì, ottimo punto. Ciò lo renderebbe abbastanza flessibile da supportare i cambiamenti. – Starx

2

soluzione di Starx è stato estremamente utile per me. Ma ho avuto alcuni problemi quando ho provato ad implementare una barra laterale a scorrimento verticale con esso. Qui è stato il mio codice iniziale, in base a ciò che ha scritto Starx:

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

E 'un po' diverso dalla soluzione di Starx, perché penso che il suo codice è progettato per consentire un menu a galleggiare in orizzontale anziché in verticale. Ma questo è solo un accostamento. Il problema che ho riscontrato con il codice precedente è che in molti browser o in base al carico di risorse del computer, i movimenti del menu risulterebbero instabili, mentre la soluzione iniziale di css era semplice e fluida. Lo attribuisco al fatto che i browser sono più lenti a lanciare eventi javascript piuttosto che a implementare css.

La mia soluzione alternativa a questo problema di choppiness è impostare la cornice su fisso anziché su assoluto, quindi annullare i movimenti orizzontali usando il metodo di Starx.

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

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

Si potrebbe dire che tutto quello che sto facendo è scambiato choppiness scorrimento verticale per choppiness lo scorrimento orizzontale. Ma il fatto è che il 99% dello scrolling è verticale, ed è molto più fastidioso quando è choppy rispetto a quando lo scrolling orizzontale è.

Ecco il mio post relativo a questo proposito, se non ho già esaurito la pazienza di tutti: Fixing a menu in one direction in jquery

0

Mi rendo conto che questa discussione è potente vecchio ma mi ha aiutato a venire con una soluzione per il mio progetto.

Nel mio caso avevo un'intestazione che non volevo mai essere inferiore a 1000px, intestazione sempre in primo piano, con contenuti che potessero andare a destra illimitata.

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', ''); 
     } 
    }); 

Questo dovrebbe anche gestire quando il browser è inferiore intestazioni min-width

0

Ho appena posizione aggiunto: assoluta e che ha risolto il mio problema.

+5

Il posizionamento assoluto corregge gli elementi relativi al documento. Il posizionamento fisso li corregge rispetto alla finestra. Se si utilizza il problema risolto in assoluto, non si ha lo stesso problema di questa domanda. – Niall

1

Questo è un thread molto vecchio, ma ho trovato una soluzione CSS pura a questo usando un po 'di nidificazione creativa. Non ero un fan del metodo jQuery a tutti ...

Fiddle qui: 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

La soluzione richiede però di scorrere il div contenitore del contenuto anziché la finestra effettiva, il che è ben lungi dall'essere l'ideale: il tuo violino ne dimostra il motivo. Il contenuto è in esecuzione sul lato destro della pagina, ma la barra di scorrimento orizzontale non è sullo schermo. Questo è un grosso problema di usabilità. – Niall

0

Aggiornato lo script per controllare la posizione di partenza:

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

}

6

Se il blocco è originariamente posizionato come statico, si consiglia di provare questo

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

0

Su div genitore è possibile aggiungere

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

Grazie

0

Molto facile soluzione è:

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

dovresti usare CSS3 'position: fixed' per questo piuttosto che andare per la soluzione js –

0

Sì, in realtà si può farlo solo utilizzando CSS ...

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

Dimmi se funziona

Problemi correlati