gpt4 book ai didi

javascript - 交换内部 css 位置时使用 css 和 javascript 的下拉菜单不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 09:49:05 25 4
gpt4 key购买 nike

这行得通

 .c1
{
background-color:red;
position:relative;
}
.c2
{
background-color:blue;
position:absolute;
height:50px;
width:100px;
display:none;}

.show
{
display:block;
}

<body>
<button class="c1" onclick="myfunction()">click</button>
<div id="change" class="c2">drop </div>

<script>
function myfunction(){
document.getElementById("change").classList.toggle("show")
}
</script>

但是交换 .show 和 .c2,是行不通的。

.c1
{
background-color:red;
position:relative;
}
.show
{
display:block;
}

.c2
{
background-color:blue;
position:absolute;
height:50px;
width:100px;
display:none;}



<body>
<button class="c1" onclick="myfunction()">click</button>
<div id="change" class="c2">drop </div>

<script>
function myfunction(){
document.getElementById("change").classList.toggle("show")
}
</script>

可能是因为我用过classList.toggle的缘故。
它将划分的显示从无更改为 block 。唯一的代码更改是 .c2 类和 .show 类位置。css 类的顺序重要吗?

最佳答案

也许第一眼看起来很奇怪,但如果你想到 css 如何对声明进行排序,这实际上是很合乎逻辑的,这被称为特异性。对于每个前端开发人员来说,最好至少阅读一次优秀而广泛的 guide at MDN .

来自指南:

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of CSS selectors of different sorts.

例如,位于文档底部的声明具有更高的优先级,并且将应用这些声明。例如,如果您有以下声明,您的背景将为蓝色。

body { background: red; }
...
body { background: blue; }

但是越具体越重要,越具体的声明就会适用。所以虽然一开始有点违反直觉,但背景下面的代码实际上是红色的:

html body { background: red; }
...
body { background: blue; }

回到您的示例:具有类 .show 的元素应该显示为 block 元素,但是如果您在 另一个类的声明之前有该类的声明应用于同一元素的类(在本例中为 .c2),它将被覆盖。但是,您可以通过更具体来覆盖它:

.c2.show { display: block; }
.c2 { display: none; }

<div class="c2"><!-- This element is hidden --></div>
<div class="c2 show"><!-- This element is shown --></div>

您应该尽可能避免 !important,因为它有时会让人不清楚为什么要应用 css 声明,并且更难覆盖它。基本上,它几乎从来没有必要。

关于javascript - 交换内部 css 位置时使用 css 和 javascript 的下拉菜单不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39248546/

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