我有一个像这样的 html 按钮:
<button autofocus role="button" ng-disabled="something.$invalid">{{ Continue }}</button>
该按钮最初被禁用,因此自动对焦属性没有任何效果。我想要发生的是,当按钮启用时,我希望立即将焦点放在按钮上。
我怎样才能做到这一点?
编辑:如下所述,监视值然后将焦点设置到元素的指令是解决此问题的一种方法。我尝试创建与下面相同的指令,但焦点似乎没有设置。
最佳答案
正如评论中提到的,指令对此很有好处。下面将观察模型并传递给它,并在它变为 true 时关注元素。
module.directive('focusToMe', function($parse) {
return {
restrict: 'A',
compile: function() {
var directiveName = this.name;
return function(scope, element, attrs) {
scope.$watch(attrs[directiveName], function(newVal, oldVal) {
if (newVal) {
element.focus();
}
})
}
}
}
});
然后您可以将其添加到按钮元素中:
<button autofocus role="button" ng-disabled="something.$invalid" focus-to-me="something.$invalid">{{ Continue }}</button>
关于javascript - 按钮启用后如何聚焦?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29761468/