angularjs锚点的使用

有很多人在使用ng-view时都用到了#号做route,所以如果在页面上需要用到锚点的时候就会比较头疼了。这个时候可以使用ng的anchorScroll,也可以使用jsGen中封装的anchorScroll。推荐使用jsGen中的anchorScroll。

services.js

.factory('anchorScroll', function () {
    function toView(element, top, height) {
        var winHeight = $(window).height();

        element = $(element);
        height = height > 0 ? height : winHeight / 10;
        $('html, body').animate({
            scrollTop: top ? (element.offset().top - height) : (element.offset().top + element.outerHeight() + height - winHeight)
        }, {
            duration: 200,
            easing: 'linear',
            complete: function () {
                if (!inView(element)) {
                    element[0].scrollIntoView( !! top);
                }
            }
        });
    }

    function inView(element) {
        element = $(element);

        var win = $(window),
            winHeight = win.height(),
            eleTop = element.offset().top,
            eleHeight = element.outerHeight(),
            viewTop = win.scrollTop(),
            viewBottom = viewTop + winHeight;

        function isInView(middle) {
            return middle > viewTop && middle < viewBottom;
        }

        if (isInView(eleTop + (eleHeight > winHeight ? winHeight : eleHeight) / 2)) {
            return true;
        } else if (eleHeight > winHeight) {
            return isInView(eleTop + eleHeight - winHeight / 2);
        } else {
            return false;
        }
    }

    return {
        toView: toView,
        inView: inView
    };
})

使用方式 直接使用:app.anchorScroll.toView('#test', true);

    controller
    $scope.demo = function(){
        app.anchorScroll.toView('#test', true);
    };
    view:
    <a href="" ng-click="demo();">test</a>
    <div id="test"></div>
posted @ 2016-06-06 16:16  ShirleyHe  阅读(2864)  评论(0编辑  收藏  举报