我试图在有人通过表单中的输入字段选项卡时向上或向下滚动页面。我希望当用户选中时,当前聚焦的输入元素将在页面中间垂直居中。我为此写了一个指令,但它没有像我期望的那样工作。
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函数以返回一个对象{link:...}, 另外,使用了elem.prop(....)