2016-07-23 97 views
1

我试图在某人通过表单中的输入字段标记页面时向上或向下滚动页面。我希望当用户选中时,当前关注的输入元素将在页面中间垂直居中。我为此写了一个指令,但它不起作用,就像我期望的那样。如何将页面滚动到输入字段焦点上的中间位置

angular 
    .module('app') 
    .directive('formScroll', formScroll); 

function formScroll($window) { 

     function link(scope, elem) { 
      elem.bind('focus', function() { 
       var offset, 
        elOffset = elem.offset().top, 
        elHeight = elem.height(), 
        windowHeight = $window.innerHeight; 

       offset = elOffset - ((windowHeight - elHeight)/2); 

       $window.scrollTo(0, offset); 
      }); 
     } 
    } 
+0

能否请您详细阐述*隐而不宣”像我期望的那样工作*意味着什么? –

回答

0
var app = angular.module('plunker', []); 
app.controller('MainCtrl', function($scope) { 
    $scope.name = 'World'; 
}); 

app.directive('formScroll', formScroll); 
    function formScroll($window) { 
     return { 
     link: function(scope, elem) { 
       elem.bind('focus', function() { 
        var offset, 
       elOffset = elem.prop('offsetTop'), //.offset().top, 
       elHeight = elem.prop('height'), //elem.height(), 
       windowHeight = $window.innerHeight; 
       offset = elOffset - ((windowHeight - elHeight)/2); 
       $window.scrollTo(0, offset); 
       }); 
     } 
     } 
    } 

我修改了formScroll函数返回一个对象{链接:...}, 另外,使用elem.prop(....)

相关问题