【发布时间】:2015-05-26 08:15:31
【问题描述】:
我正在使用 AngularJS 开发一个网络应用程序。我有一个不知从哪里出现的错误,它工作正常,我真的不知道为什么它不再工作了。
所以它在指令中,我尝试在指令html模板中设置元素的属性offsetWidth。因为我真的不知道它来自哪里,所以我会给你我的指令和模板的完整代码。该指令创建一个应用程序按钮并在单击时处理其视觉效果。触发错误的是$element[0].offsetWidth = $element[0].offsetWidth; 行。 (重启动画是个技巧)
我再重复一遍,这段代码运行良好,我几乎可以肯定我没有进行任何更改。我是用Chrome调试的,可能是来源于它吧?
错误:Uncaught TypeError: Cannot set property offsetWidth of #<HTMLElement> which has only a getter
指令:
'use strict';
XVMApp.directive('appButton', ['$location', function($location){
return {
restrict: 'E',
replace: true,
scope: {
img: '@',
fillPercent: '@?',
target: '@?'
},
link: function ($scope, $element) {
// Image percentage fill button
if($scope.fillPercent === undefined) $scope.fillPercent = '100';
// Click event
$element.on('click', function() {
// Url target
if($scope.target !== undefined){
$scope.$apply(function() {
$location.path($scope.target);
});
}
// Click effect
$element[0].preventDefault;
$element[0].classList.remove('app-button-click-effect');
$element[0].offsetWidth = $element[0].offsetWidth;
$element[0].classList.add('app-button-click-effect');
});
},
templateUrl: 'src/directive/appButton/app-button.html'
};
}]);
模板:
<div class="app-button"
style="background-size: {{fillPercent}}%; ">
<div style="
background-image: url('src/assets/img/{{img}}');
background-repeat: no-repeat;
background-position: center;
background-size: {{fillPercent}}%;
height: 100%;
width: 100%; ">
</div>
</div>
【问题讨论】:
-
如果我只获得 offsetWidth 值,重新启动动画技巧仍然有效($element[0].offsetWidth;),所以我的问题得到了解决。但我仍然想知道为什么我不能为 offsetWidth 属性设置值?
标签: javascript angularjs web-applications angularjs-directive