gpt4 book ai didi

javascript - ng-class 无法将 css 类应用于元素

转载 作者:行者123 更新时间:2023-11-29 19:08:09 25 4
gpt4 key购买 nike

我的代码中某处有这个 div。

<div ng-class="className" >{{className}}</div>

在某些时候,我通过 ng-click 调用 changeClass 函数来更改此 div 的类。

     $scope.changeClass = function(){
console.log($scope.className)
if ($scope.className === "expand-icon")
$scope.className = "expand-icon.expanded";
else
$scope.className = "expand-icon";
};

我可以看到类因 console.log 而发生变化,并且 {{className}} 也在页面上输出。但是,似乎没有应用 css 类。

它实际上是一个“+”号,需要用动画变成“-”。这是 CSS:

 /* + button */

.expand-icon {
height: 32px;
width: 32px;
position: relative;
}
.expand-icon::before, .expand-icon::after {
content: " ";
width: 32px;
height: 6px;
background-color: #fff;
display: block;
position: absolute;
top: 50%;
left: 50%;
transition: all 0.15s cubic-bezier(.42, 0, .58, 1);
opacity: 1;
border-radius: 2px;
}
.expand-icon::before {
transform: translate(-50%, -50%) rotate(90deg);
}
.expand-icon::after {
transform: translate(-50%, -50%);
}

.expand-icon {
height: 32px;
width: 32px;
position: relative;
}
.expand-icon.expanded::before {
transform: translate(-50%, -50%) rotate(0deg);
}
.expand-icon.expanded::after {
transform: translate(-50%, -50%) rotate(-90deg);
opacity: 0;
}

因此应用了 expand-icon 但 expand-icon.expanded 没有任何影响,因为我正在使用这个 ng-class 技巧。知道为什么吗?

最佳答案

您应该用空格替换点:$scope.className = "expand-icon expanded";

或者更好的是,使用 ng-class 的其他表示法:

// probably rename it to something like $scope.toggleExpanded()
$scope.changeClass = function(){
$scope.expanded = !$scope.expanded;
};

在你的 html 中:

<div class="expand-icon"
ng-class="{ expanded: expanded }">{{className}}</div>

这将始终应用您的 expand-icon 类,并且仅当 $scope.expanded 属性为真时才应用 expanded 类。

关于javascript - ng-class 无法将 css 类应用于元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41164988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com