在滚动上更改margin-top

时间:2013-10-10 08:12:52

标签: jquery css scroll margin

我在div上有一个负余量,但我想改变滚动的负边距,直到负数达到0。

margin:-150px 0 0 0;

to :(滚动)

margin:0px 0 0 0;

我认为这是某种视差效果,我正在搜索并在StackOverflow上找到它: Change margin top of div based on window scroll

我想到了类似的东西,但必须有更轻松的东西

$(window).scroll(function(){
if  ($(window).scrollTop() >= 1){ $('#three').css({margin:'-149px 0 0 0px'}); }
if  ($(window).scrollTop() >= 2){ $('#three').css({margin:'-148px 0 0 0px'}); }  
if  ($(window).scrollTop() >= 3){ $('#three').css({margin:'-147px 0 0 0px'}); }   
if  ($(window).scrollTop() >= 4){ $('#three').css({margin:'-146px 0 0 0px'}); }  
else { $('#three').css({margin:'-150px 0 0 0px'}); }
});

-

我用html / css基础创建了一个小提琴

小提琴: http://jsfiddle.net/qSe4e/

-

非常感谢高级

2 个答案:

答案 0 :(得分:9)

尝试使用一点点数学运算来自动生成所有可能性(类似于您的尝试,但只有一行代替每一种可能性。

示例:http://jsfiddle.net/qSe4e/9/

$(window).scroll(function(){
    var fromTop = $(window).scrollTop();
    $("#three").css('margin', '-' + (100 - fromTop) + 'px 0px 0px 0px');
});

答案 1 :(得分:1)

这样做

$(document).scroll(function () {
$("#three").animate({margin: "0px 0px 0px 0px"}, 3000);
});

Demo Fiddle

相关问题