2011-12-27 9 views

Respuesta

112

Usted puede encontrar un ejemplo a continuación. Básicamente se adjunta una función a window 's scroll evento y trace scrollTop propiedad y si es más alto que el umbral deseado aplica position: fixed y algunas otras propiedades CSS.

jQuery(function($) { 
 
    function fixDiv() { 
 
    var $cache = $('#getFixed'); 
 
    if ($(window).scrollTop() > 100) 
 
     $cache.css({ 
 
     'position': 'fixed', 
 
     'top': '10px' 
 
     }); 
 
    else 
 
     $cache.css({ 
 
     'position': 'relative', 
 
     'top': 'auto' 
 
     }); 
 
    } 
 
    $(window).scroll(fixDiv); 
 
    fixDiv(); 
 
});
body { 
 
    height: 2000px; 
 
    padding-top: 100px; 
 
} 
 
#getFixed { 
 
    color: #c00; 
 
    font: bold 15px arial; 
 
    padding: 10px; 
 
    margin: 10px; 
 
    border: 1px solid #c00; 
 
    width: 200px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
 
<div id="getFixed">This div is going to be fixed</div>

+1

Solución fantástica, muy adaptable a la mayoría de las situaciones, Felicitaciones, señor. – jlstr

+0

gr8 respuesta !! : D –

+0

¡Mucho más simple que mi implementación anterior! – socca1157

14

En jQuery para los diseñadores hay una publicación bien escrita sobre esto, este es el fragmento jQuery que hace la magia. simplemente reemplace #comment con el selector del div que desea flotar.

Nota: Para ver el artículo completo entra aquí: http://jqueryfordesigners.com/fixed-floating-elements/

$(document).ready(function() { 
    var $obj = $('#comment'); 
    var top = $obj.offset().top - parseFloat($obj.css('marginTop').replace(/auto/, 0)); 

    $(window).scroll(function (event) { 
    // what the y position of the scroll is 
    var y = $(this).scrollTop(); 

    // whether that's below the form 
    if (y >= top) { 
     // if so, ad the fixed class 
     $obj.addClass('fixed'); 
    } else { 
     // otherwise remove it 
     $obj.removeClass('fixed'); 
    } 
    }); 
}); 
+1

obras genial cuando cambias el nombre de var "top" a otro nombre, pero es un poco molesto reemplazar todo el comentario, debes usar un objeto para eso. –

2
(function($) { 
    var triggers = []; 
    $.fn.floatingFixed = function(options) { 
    options = $.extend({}, $.floatingFixed.defaults, options); 
    var r = $(this).each(function() { 
     var $this = $(this), pos = $this.position(); 
     pos.position = $this.css("position"); 
     $this.data("floatingFixedOrig", pos); 
     $this.data("floatingFixedOptions", options); 
     triggers.push($this); 
    }); 
    windowScroll(); 
    return r; 
    }; 

    $.floatingFixed = $.fn.floatingFixed; 
    $.floatingFixed.defaults = { 
    padding: 0 
    }; 

    var $window = $(window); 
    var windowScroll = function() { 
    if(triggers.length === 0) { return; } 
    var scrollY = $window.scrollTop(); 
    for(var i = 0; i < triggers.length; i++) { 
     var t = triggers[i], opt = t.data("floatingFixedOptions"); 
     if(!t.data("isFloating")) { 
     var off = t.offset(); 
     t.data("floatingFixedTop", off.top); 
     t.data("floatingFixedLeft", off.left); 
     } 
     var top = top = t.data("floatingFixedTop"); 
     if(top < scrollY + opt.padding && !t.data("isFloating")) { 
     t.css({position: 'fixed', top: opt.padding, left: t.data("floatingFixedLeft"), width: t.width() }).data("isFloating", true); 
     } else if(top >= scrollY + opt.padding && t.data("isFloating")) { 
     var pos = t.data("floatingFixedOrig"); 
     t.css(pos).data("isFloating", false); 
     } 
    } 
    }; 

    $window.scroll(windowScroll).resize(windowScroll); 
})(jQuery); 

y luego hacer cualquier div como flotante fijo llamando

$('#id of the div').floatingFixed(); 

fuente: https://github.com/cheald/floatingFixed

10

Hice una mezcla de las respuestas aquí, se llevó el código de @Julian y las ideas de los demás, Parece claro para mí, esto es lo que queda:

fiddlehttp://jsfiddle.net/wq2Ej/

jQuery

//store the element 
var $cache = $('.my-sticky-element'); 

//store the initial position of the element 
var vTop = $cache.offset().top - parseFloat($cache.css('marginTop').replace(/auto/, 0)); 
    $(window).scroll(function (event) { 
    // what the y position of the scroll is 
    var y = $(this).scrollTop(); 

    // whether that's below the form 
    if (y >= vTop) { 
     // if so, ad the fixed class 
     $cache.addClass('stuck'); 
    } else { 
     // otherwise remove it 
     $cache.removeClass('stuck'); 
    } 
    }); 

css:

.my-sticky-element.stuck { 
    position:fixed; 
    top:0; 
    box-shadow:0 2px 4px rgba(0, 0, 0, .3); 
} 
Cuestiones relacionadas