angularjs中,ng-hide隐藏的元素,设置不了style

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/rencaishigepi/article/details/82718052

做一个搜索历史框,input获得焦点就显示搜索历史框,框宽度与input框同宽(因为input后还有一个搜索按钮呢)否则不显示。

在获得焦点的函数中,已经把flag赋值为true了,却还是不能执行下面的宽度设置值;

<input class='form-control' ng-model='criteria.keyword' placeholder='输入搜索关键字' ng-focus="togglePanel($event)" ng-blur="flag=false">
<ul class="history-panel" ng-if="historyRecords.length" ng-show="flag">
    <li class="history-item" ng-repeat="record in historyRecords" ng-click="chooseHistoryRecord(record)">{{record}}</li>
</ul>

$scope.togglePanel = function($event) {
        $scope.flag = true;
        var inputWidth = $event.target.offsetWidth;
        document.querySelector('.history-panel').style.width = inputWidth;
}

最后调试突然醒悟,应该是:
**第一,即使你设置了为true,angularjs的绑定还需要一段时间,这时的元素依然是隐藏的;
第二,ng-hide使用的是display:none !important的css,大家都知道了,display:none的元素是不占空间的,所以你获取不到元素的一些样式值;**
所以在逻辑中即使写了设置width,是无效的。
最后,综合了移动端的展示,把ul的宽度设置为了100%;那些事件也就可以删除了,在页面中初始化flag就可以了。

猜你喜欢

转载自blog.csdn.net/rencaishigepi/article/details/82718052