将css位置转换为jquery平滑滑动

时间:2013-01-17 13:16:36

标签: jquery css

我目前有一个<div>,当页面向上或向下移动时,它保持位于页面左侧顶部的位置。这很好用,但不是很顺利。

我正在考虑重新考虑下面的代码,以使其顺利滚动。目前,当触发器发生时,它只是设置了CSS top属性 - 这使它“变得紧张”。我有点不确定如何使这个平滑的滚动动作反对将css顶部值设置为其确切位置

        //scrolling menu
    if($("#selectedOptions").length > 0){   //if the element exists
        $(window).scroll(function(){
            var div = $("#selectedOptions");        // the div that slides
            if(div) {                               
                var pos = div.parent().position().top;  //position of the top of the wrapper
                var windowPos = $(window).scrollTop();  //current window postion

                //top of moving div not to go further than
                var bottom = $("#sizeAndQuantHeader").position().top; //where the div shouldn't go past 

                //de-bug
                //console.log("pos: " + pos + " - winpos" + windowPos + ", heih: " + divHieght + " doc he: " + $(document).height() + " bott" + bottom);

                //if between the range then display at new postion
                if (windowPos > pos && (windowPos < bottom)) {
                    div.css("top", windowPos-pos);
                    //must be higher than its current position so set to 0
                 } else if (windowPos < pos && windowPos < bottom) {
                     div.css("top", 0);
                } 
            }
        });
    }

有关如何在页面上顺利滚动<div>的任何帮助或提示都会非常感激。

**更新

不幸的是,我的元素已经滚动到不同的页面区域:

var _scrollTo = function(div){
    $('html,body').animate({
        scrollTop: div.offset().top},
        'slow');
}; 

现在,当调用上面的函数时,我认为它会触发调用:

  $(window).scroll(function(){animate div...

并延迟滚动新动画div。我不能使用回叫,因为它在其他地方重新使用。我可能在这里遗漏了一些东西,所以我又回到了没有动画的地步。

3 个答案:

答案 0 :(得分:2)

使用Animate使其平滑。

div.animate({ top: windowPos-pos }, 300);

答案 1 :(得分:1)

关键是在这里更改此代码:

if (windowPos > pos && (windowPos < bottom)) {
    div.css("top", windowPos-pos);
    //must be higher than its current position so set to 0
} else if (windowPos < pos && windowPos < bottom) {
    div.css("top", 0);
} 

if (windowPos > pos && (windowPos < bottom)) {
    div.animate({top: windowPos-pos}, 100);
    //must be higher than its current position so set to 0
} else if (windowPos < pos && windowPos < bottom) {
    div.animate({top: "0"}, 100);
} 

jQuery's animate()非常易于使用/操作。

答案 2 :(得分:0)

将css添加到div(#selectedOptions)

transition: all 0.5s ease 0s;
-moz-transition: all 0.5s ease 0s;
-webkit-transition: all 0.5s ease 0s;
-o-transition: all 0.5s ease 0s;

它将自动流畅。

相关问题