<style>
.scrollToTop {
position: fixed;
bottom: 70px;
right: 15px;
width: 45px;
height: 45px;
border-radius: 25px;
background: url(/forum/img/toTop.png) center center no-repeat rgba(0,0,0,.4);
background-size: 50% 25%;
}
</style>
//回到顶部
app.directive('scrollTop', function ($window, $document, $compile) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
var elShare = angular.element('<a title="返回顶部" ng-click="goTop()" class="scrollToTop"></a>');
function showShare() {
if (!elShare.hasClass('ng-scope')) {
$compile(elShare)($scope);
var body = $document.find('body').eq(0);
body.append(elShare);
}
elShare.show();
}
var loading = false;
$scope.goTop = function () {
var idToScroll = attr.href;
var $target;
if (idToScroll) {
$target = $(idToScroll);
} else {
$target = elem;
}
loading = true;
$("body").animate({ scrollTop: $target.offset().top }, "fast", function () {
elShare.hide();
loading = false;
});
}
//http://stackoverflow.com/questions/13549216/changing-css-on-scrolling-angular-style
var scrollTop = 0;
var windowEl = angular.element($window);
var handler = function () {
if (loading) return;
var ele = document.body;
if (ele.scrollTop > 50 && scrollTop < ele.scrollTop) {
showShare();
}
else {
elShare.hide();
}
scrollTop = document.body.scrollTop;
}
windowEl.on('scroll', $scope.$apply.bind($scope, handler));
handler();
}
};
});