Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 平滑滚动到页面上的特定元素_Javascript_Jquery_Animation_Scroll_Jquery Animate - Fatal编程技术网

Javascript 平滑滚动到页面上的特定元素

Javascript 平滑滚动到页面上的特定元素,javascript,jquery,animation,scroll,jquery-animate,Javascript,Jquery,Animation,Scroll,Jquery Animate,我想在页面的开头有4个按钮/链接,下面是内容 我在按钮上写下以下代码: <a href="#idElement1">Scroll to element 1</a> <a href="#idElement2">Scroll to element 2</a> <a href="#idElement3">Scroll to element 3</a> <a href="#idElement4">Scroll to el

我想在页面的开头有4个按钮/链接,下面是内容

我在按钮上写下以下代码:

<a href="#idElement1">Scroll to element 1</a>
<a href="#idElement2">Scroll to element 2</a>
<a href="#idElement3">Scroll to element 3</a>
<a href="#idElement4">Scroll to element 4</a>
有什么建议吗?多谢各位


编辑:和小提琴:

你可以使用这个插件。这正是你想要的

平滑滚动-无需jQuery 基于此,我在没有外部库的情况下创建了一个

javascript非常简单。首先是一个辅助函数,用于改进跨浏览器支持,以确定当前位置

function currentYPosition() {
    // Firefox, Chrome, Opera, Safari
    if (self.pageYOffset) return self.pageYOffset;
    // Internet Explorer 6 - standards mode
    if (document.documentElement && document.documentElement.scrollTop)
        return document.documentElement.scrollTop;
    // Internet Explorer 6, 7 and 8
    if (document.body.scrollTop) return document.body.scrollTop;
    return 0;
}
然后是一个函数,用于确定目标元素的位置—我们希望滚动到的位置

function elmYPosition(eID) {
    var elm = document.getElementById(eID);
    var y = elm.offsetTop;
    var node = elm;
    while (node.offsetParent && node.offsetParent != document.body) {
        node = node.offsetParent;
        y += node.offsetTop;
    } return y;
}
和做滚动的核心功能

function smoothScroll(eID) {
    var startY = currentYPosition();
    var stopY = elmYPosition(eID);
    var distance = stopY > startY ? stopY - startY : startY - stopY;
    if (distance < 100) {
        scrollTo(0, stopY); return;
    }
    var speed = Math.round(distance / 100);
    if (speed >= 20) speed = 20;
    var step = Math.round(distance / 25);
    var leapY = stopY > startY ? startY + step : startY - step;
    var timer = 0;
    if (stopY > startY) {
        for ( var i=startY; i<stopY; i+=step ) {
            setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
            leapY += step; if (leapY > stopY) leapY = stopY; timer++;
        } return;
    }
    for ( var i=startY; i>stopY; i-=step ) {
        setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
        leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
    }
    return false;
}
函数平滑滚动(eID){
var startY=currentYPosition();
var stopY=elmYPosition(eID);
var距离=停止>开始?停止-开始:开始-停止;
如果(距离<100){
滚动到(0,停止);返回;
}
var速度=数学圆(距离/100);
如果(速度>=20)速度=20;
var步长=数学圆(距离/25);
var leapY=stopY>startY?startY+step:startY-step;
var定时器=0;
如果(停止>开始){
for(var i=startY;i stopY)leapY=stopY;timer++;
}返回;
}
对于(变量i=开始;i>停止;i-=步骤){
设置超时(“窗口滚动到(0,+leapY+”),计时器*速度);
leapY-=步长;如果(leapY
你只要做以下的事情就可以了。通过将id用作元素的引用,可以创建指向另一个元素的链接

平滑滚动到id为anchor-2的标题
...
...  一些内容
...
主播2
版权 在itnewb.com的页脚中写着如下内容:
itnewb文章中演示的技术、效果和代码可用于任何目的,无需归属(尽管我们建议使用)
(2014-01-12)

使用jQuery.ScrollTo平滑滚动 要使用jQuery ScrollTo插件,必须执行以下操作

  • href
    指向另一个elements.id的位置创建链接
  • 创建要滚动到的元素
  • 参考jQuery和scrollTo插件
  • 确保为每个应该进行平滑滚动的链接添加一个click事件处理程序
  • 创建链接

    <h1>Smooth Scrolling with the jQuery Plugin .scrollTo</h1>
    <div id="nav-list">
      <a href="#idElement1">Scroll to element 1</a>
      <a href="#idElement2">Scroll to element 2</a>
      <a href="#idElement3">Scroll to element 3</a>
      <a href="#idElement4">Scroll to element 4</a>
    </div>
    
    设置对脚本的引用。您的文件路径可能不同

    <script src="./jquery-1.8.3.min.js"></script>
    <script src="./jquery.scrollTo-1.4.3.1-min.js"></script>
    

    只是在下面做了这个javascript唯一的解决方案

    简单用法:

    EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);
    
    引擎对象(您可以摆弄过滤器、fps值):

    /**
    *
    *Borbás Geri于2013年12月17日创作
    *版权所有(c)2013 eppz!发展有限责任公司。
    *
    *特此免费授予获得本软件及相关文档文件(“软件”)副本的任何人在不受限制的情况下经营本软件的权利,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或出售本软件副本的权利,并允许向其提供软件的人员在符合以下条件的情况下这样做:
    *上述版权声明和本许可声明应包含在软件的所有副本或实质部分中。
    *本软件按“原样”提供,无任何明示或暗示的担保,包括但不限于适销性、特定用途适用性和非侵权性担保。在任何情况下,作者或版权持有人均不对任何索赔、损害赔偿或其他责任负责,无论是合同诉讼、侵权诉讼还是其他诉讼,均由本软件或本软件的使用或其他交易引起,或与本软件或本软件的使用或其他交易有关。
    *
    */
    变量eppzto=
    {
    /**
    *帮手。
    */
    documentVerticalScrollPosition:函数()
    {
    if(self.pageYOffset)返回self.pageYOffset;//Firefox、Chrome、Opera、Safari。
    if(document.documentElement&&document.documentElement.scrollTop)返回document.documentElement.scrollTop;//Internet Explorer 6(标准模式)。
    if(document.body.scrollTop)返回document.body.scrollTop;//Internet Explorer 6、7和8。
    返回0;//以上都没有。
    },
    视口高度:函数()
    {return(document.compatMode==“CSS1Compat”)?document.documentElement.clientHeight:document.body.clientHeight;},
    documentHeight:function()
    {返回(document.height!==未定义)?document.height:document.body.offsetHeight;},
    documentMaximumScrollPosition:函数()
    {返回this.documentHeight()-this.viewportHeight();},
    elementVerticalClientPositionById:函数(id)
    {
    var元素=document.getElementById(id);
    var rectangle=element.getBoundingClientRect();
    返回矩形.top;
    },
    /**
    *动画滴答声。
    */
    scrollVerticalTickToPosition:功能(currentPosition,targetPosition)
    {
    var滤波器=0.2;
    var fps=60;
    var差异=parseFloat(targetPosition)-parseFloat(currentPosition);
    //抓拍,到达后停止。
    var arrived=(Math.abs(差异)maximumScrollPosition)targetPosition=maximumScrollPosition;
    //启动动画。
    此。滚动垂直滴答位置(currentPosition,targetPosition);
    }
    };
    
    我已经用了很长时间了:

    function scrollToItem(item) {
        var diff=(item.offsetTop-window.scrollY)/8
        if (Math.abs(diff)>1) {
            window.scrollTo(0, (window.scrollY+diff))
            clearTimeout(window._TO)
            window._TO=setTimeout(scrollToItem, 30, item)
        } else {
            window.scrollTo(0, item.offsetTop)
        }
    }
    
    用法:
    scrollToItem(element)
    其中
    element
    document.getElementById('elementid')
    例如。

    使用
    requestAnimationFrame时非常平滑
    对于平滑渲染的滚动动画,可以使用比常规的
    setTimeout()
    解决方案更好的方法

    一个基本示例如下所示。为浏览器的每个动画帧调用函数
    step
    ,可以更好地管理重新绘制的时间,从而提高性能

    函数doscorling(元素,持续时间){
    var startingY=window.pageYOffset;
    变量d
    
    <h2 id="idElement1">Element1</h2>    
    ....
    <h2 id="idElement1">Element1</h2>
    ... 
    <a class="toNav" href="#nav-list">Scroll to Nav-List</a>
    
    <script src="./jquery-1.8.3.min.js"></script>
    <script src="./jquery.scrollTo-1.4.3.1-min.js"></script>
    
    jQuery(function ($) {
        $.easing.elasout = function (x, t, b, c, d) {
            var s = 1.70158;  var p = 0; var a = c;
            if (t == 0) return b;
            if ((t /= d) == 1) return b + c;
            if (!p) p = d * .3;
            if (a < Math.abs(c)) {
                a = c;   var s = p / 4;
            } else var s = p / (2 * Math.PI) * Math.asin(c / a);
            // line breaks added to avoid scroll bar
            return a * Math.pow(2, -10 * t)  * Math.sin((t * d - s) 
                     * (2 * Math.PI) / p) + c + b;
        };            
    
        // important reset all scrollable panes to (0,0)       
        $('div.pane').scrollTo(0); 
        $.scrollTo(0);    // Reset the screen to (0,0)
        // adding a click handler for each link 
        // within the div with the id nav-list
        $('#nav-list a').click(function () {             
            $.scrollTo(this.hash, 1500, {
                easing: 'elasout'
            });
            return false;
        });   
        // adding a click handler for the link at the bottom
        $('a.toNav').click(function () { 
            var scrollTargetId = this.hash;
            $.scrollTo(scrollTargetId, 1500, {
                easing: 'elasout'
            });
            return false;
        });    
    });
    
     $(document).ready(function () {
        $('.navSection').on('click', function (e) {
            debugger;
            var elemId = "";    //eg: #nav2
            switch (e.target.id) {
            case "nav1":
                elemId = "#s1";
                break;
            case "nav2":
                elemId = "#s2";
                break;
            case "nav3":
                elemId = "#s3";
                break;
            case "nav4":
                elemId = "#s4";
                break;
            }
            $('.content').animate({
                scrollTop: $(elemId).parent().scrollTop() 
                        + $(elemId).offset().top 
                        - $(elemId).parent().offset().top
            }, {
                duration: 1000,
                specialEasing: { width: 'linear'
                        , height: 'easeOutBounce' },
                complete: function (e) {
                    //console.log("animation completed");
                }
            });
            e.preventDefault();
        });
      });
    
    EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);
    
    /**
     *
     * Created by Borbás Geri on 12/17/13
     * Copyright (c) 2013 eppz! development, LLC.
     *
     * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
     * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     *
     */
    
    
    var EPPZScrollTo =
    {
        /**
         * Helpers.
         */
        documentVerticalScrollPosition: function()
        {
            if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari.
            if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode).
            if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8.
            return 0; // None of the above.
        },
    
        viewportHeight: function()
        { return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; },
    
        documentHeight: function()
        { return (document.height !== undefined) ? document.height : document.body.offsetHeight; },
    
        documentMaximumScrollPosition: function()
        { return this.documentHeight() - this.viewportHeight(); },
    
        elementVerticalClientPositionById: function(id)
        {
            var element = document.getElementById(id);
            var rectangle = element.getBoundingClientRect();
            return rectangle.top;
        },
    
        /**
         * Animation tick.
         */
        scrollVerticalTickToPosition: function(currentPosition, targetPosition)
        {
            var filter = 0.2;
            var fps = 60;
            var difference = parseFloat(targetPosition) - parseFloat(currentPosition);
    
            // Snap, then stop if arrived.
            var arrived = (Math.abs(difference) <= 0.5);
            if (arrived)
            {
                // Apply target.
                scrollTo(0.0, targetPosition);
                return;
            }
    
            // Filtered position.
            currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter);
    
            // Apply target.
            scrollTo(0.0, Math.round(currentPosition));
    
            // Schedule next tick.
            setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps));
        },
    
        /**
         * For public use.
         *
         * @param id The id of the element to scroll to.
         * @param padding Top padding to apply above element.
         */
        scrollVerticalToElementById: function(id, padding)
        {
            var element = document.getElementById(id);
            if (element == null)
            {
                console.warn('Cannot find element with id \''+id+'\'.');
                return;
            }
    
            var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding;
            var currentPosition = this.documentVerticalScrollPosition();
    
            // Clamp.
            var maximumScrollPosition = this.documentMaximumScrollPosition();
            if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition;
    
            // Start animation.
            this.scrollVerticalTickToPosition(currentPosition, targetPosition);
        }
    };
    
    function scrollToItem(item) {
        var diff=(item.offsetTop-window.scrollY)/8
        if (Math.abs(diff)>1) {
            window.scrollTo(0, (window.scrollY+diff))
            clearTimeout(window._TO)
            window._TO=setTimeout(scrollToItem, 30, item)
        } else {
            window.scrollTo(0, item.offsetTop)
        }
    }
    
    function scrollToItem(item) {
        var diff=(item.offsetTop-window.scrollY)/20;
        if(!window._lastDiff){
            window._lastDiff = 0;
        }
    
        console.log('test')
    
        if (Math.abs(diff)>2) {
            window.scrollTo(0, (window.scrollY+diff))
            clearTimeout(window._TO)
    
            if(diff !== window._lastDiff){
                window._lastDiff = diff;
                window._TO=setTimeout(scrollToItem, 15, item);
            }
        } else {
            console.timeEnd('test');
            window.scrollTo(0, item.offsetTop)
        }
    }
    
    function scroolTo(element, duration) {
        if (!duration) {
            duration = 700;
        }
        if (!element.offsetParent) {
            element.scrollTo();
        }
        var startingTop = element.offsetParent.scrollTop;
        var elementTop = element.offsetTop;
        var dist = elementTop - startingTop;
        var start;
    
        window.requestAnimationFrame(function step(timestamp) {
            if (!start)
                start = timestamp;
            var time = timestamp - start;
            var percent = Math.min(time / duration, 1);
            element.offsetParent.scrollTo(0, startingTop + dist * percent);
    
            // Proceed with animation as long as we wanted it to.
            if (time < duration) {
                window.requestAnimationFrame(step);
            }
        })
    }
    
    function scrollToSmoothly(pos, time){
    /*Time is only applicable for scrolling upwards*/
    /*Code written by hev1*/
    /*pos is the y-position to scroll to (in pixels)*/
         if(isNaN(pos)){
          throw "Position must be a number";
         }
         if(pos<0){
         throw "Position can not be negative";
         }
        var currentPos = window.scrollY||window.screenTop;
        if(currentPos<pos){
        var t = 10;
           for(let i = currentPos; i <= pos; i+=10){
           t+=10;
            setTimeout(function(){
            window.scrollTo(0, i);
            }, t/2);
          }
        } else {
        time = time || 2;
           var i = currentPos;
           var x;
          x = setInterval(function(){
             window.scrollTo(0, i);
             i -= 10;
             if(i<=pos){
              clearInterval(x);
             }
         }, time);
          }
    }
    
    function scrollSmoothlyToElementById(id){
       var elem = document.getElementById(id);
       scrollToSmoothly(elem.offsetTop);
    }
    
    function smoothScroll(){
        document.querySelector('.your_class or #id here').scrollIntoView({
            behavior: 'smooth'
        });
    }
    
    Region            full   + partial = sum full+partial Support
    Asia              73.24% + 22.75%  = 95.98%
    North America     56.15% + 42.09%  = 98.25%
    India             71.01% + 20.13%  = 91.14%
    Europe            68.58% + 27.76%  = 96.35%
    
    // Scroll to specific values
    // scrollTo is the same
    window.scroll({
      top: 2500, 
      left: 0, 
      behavior: 'smooth'
    });
    
    // Scroll certain amounts from current position 
    window.scrollBy({ 
      top: 100, // could be negative value
      left: 0, 
      behavior: 'smooth' 
    });
    
    // Scroll to a certain element
    document.querySelector('.hello').scrollIntoView({ 
      behavior: 'smooth' 
    });
    
    var e = document.getElementById(element);
    var top = 0;
    
    do {   
        top += e.offsetTop;
    } while (e = e.offsetParent);
    
    return top;
    
    html {
      scroll-behavior: smooth;
    }