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

标签 jquery css

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

我希望重构下面的代码,使其成为平滑的滚动条。目前,当触发器发生时,它只是设置 CSS top属性(property) - 这使得它“紧张”。我有点不确定如何使它成为一个平滑的滚动 Action ,而不是将 css top 值设置到它的确切位置

        //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 的滚动。我也不能使用回调,因为它在其他地方被重新使用。我可能在这里遗漏了一些东西,所以我又回到了没有动画的状态。

最佳答案

使用 Animate 使其流畅。

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

关于jquery - 将css位置转换为jquery平滑滑动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14379987/

相关文章:

css - 单选按钮的选中选择器被触发后,CSS 变量是否可能更改?

javascript - CSS 变换 : translateX flash bug on iOS

javascript - 如何检查字符串中的第一个字符以及如何将该字符串发送到 Jquery 中的数组中?

javascript - 使用 if 语句和 document.write 隐藏/显示 li 列表

css - 如何调整文本的垂直对齐方式以纠正字体的错位?

asp.net - 使用 javascript 函数更新 ASP.Net 中的样式

javascript - 单击项目时更改 onmouseover ="this.src=' xxx'"

jquery - FullCalendar 标题按钮垂直

javascript - Extjs滚动到tabPanel内的位置

html - 如何删除表格中行和列之间不需要的空间?