如何将Sass Ampersand或嵌套与属性选择器相结合



当self元素被禁用时,我想改变它的颜色,类似于使用sass嵌套语法的悬停。有可能实现以下目标吗?

.class {
color: blue;
&:hover {
color: grey;
}
&:[disabled] {
color: red;
}
}

我知道我可以在没有嵌套和Sass Ampersand的情况下做到这一点:

.class {
color: blue;
&:hover {
color: grey;
}
}
.class[disabled] {
color: red;
}

我很好奇这是否可以通过某种第一种解决方案来实现。

这就是DOM元素在浏览器中的外观。

<div _ngcontent-luo-c245 mat-menu-item disabled="true" class="mat-focus-indicator menu-item mat-menu-item" ng-reflect-disabled role="menuitem" tabindex="-1" aria-disabled="true">...</div>

您不需要添加方括号。它应该是这样的:

.class {
color: blue;
&:hover {
color: grey;
}
&:disabled {
color: red;
}
}

因此,我通过创建一个带有按钮的html页面来测试它,该按钮在单击时被禁用,并更改为颜色red

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="test-btn" onclick="this.disabled=true">
Test Button
</button>
</body>
</html>

scs:

body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
#test-btn {
width: max-content;
padding: 1rem;
&:hover {
color: #000;
background-color: #fff;
border-color: #fff;
}
&:disabled {
color: #fff;
background-color: #f00;
border-color: #f00;
}
}

以下是预览:点击此处

最新更新