Skip to content

Instantly share code, notes, and snippets.

@ambar
Created January 9, 2012 07:24
Show Gist options
  • Save ambar/1581655 to your computer and use it in GitHub Desktop.
Save ambar/1581655 to your computer and use it in GitHub Desktop.
sticky element
marginLeft = - ( $container.width() / 2 - parseInt($g.css('right')) - $g.innerWidth() ) = -(450 + 200 - 156)
$(function() {
if ($.support.fixedPosition) {
var $g = $('#elem'),
$w = $(window),
cls = 'elem-sticky',
padtop = 50,
inittop = $g.offset().top - padtop;
$w.scroll(function(){
$g[$w.scrollTop() > inittop ? 'addClass' : 'removeClass'](cls)
})
}
})
div.elem{
position: absolute; right: -200px; top: -38px;
}
div.elem-sticky{
position: fixed; top:20px; left:50%; margin-left: 494px;
}
@ambar
Copy link
Author

ambar commented Jan 9, 2012

  • 直接操纵 position、margin、left、top 会闪烁
  • 切换 class 效率更高

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment