javascript - 类更改时的 CSS 过渡
问题描述
width
当使用 JavaScript 向元素添加或删除某些类时,我正在尝试转换属性。如果我尝试更改 on 上的属性,则转换工作正常:hover
,但如果我尝试通过添加或删除类来转换它,它将无法正常工作。我究竟做错了什么?
function activate(number) {
var bottom1 = document.getElementById("bottom-1");
var bottom2 = document.getElementById("bottom-2");
if (number === 1) {
bottom1.classList.add("active");
bottom2.classList.remove("active");
} else {
bottom2.classList.add("active");
bottom1.classList.remove("active");
}
}
body {
display: flex;
}
.container {
position: relative;
}
.bottom-1 {
position: absolute;
bottom: 0px;
right: 0px;
height: 2px;
background-color: red;
transition: width 1s ease;
}
.bottom-2 {
position: absolute;
bottom: 0px;
left: 0px;
height: 2px;
background-color: red;
transition: width 1s ease;
}
.active {
width: 100%;
}
<div class="container">
<button onclick="activate(1)">Button 1</button>
<div id="bottom-1" class="bottom-1 transition"></div>
</div>
<div class="container">
<button onclick="activate(2)">Button 2</button>
<div id="bottom-2" class="bottom-2 transition"></div>
</div>
解决方案
您需要width
在按钮CSS
之前定义transition
:
function activate(number) {
var bottom1 = document.getElementById("bottom-1");
var bottom2 = document.getElementById("bottom-2");
if (number === 1) {
bottom1.classList.add("active");
bottom2.classList.remove("active");
} else {
bottom2.classList.add("active");
bottom1.classList.remove("active");
}
}
body {
display: flex;
}
.container {
position: relative;
}
.bottom-1 {
position: absolute;
bottom: 0px;
right: 0px;
height: 2px;
width: 0%;
background-color: red;
transition: width 1s ease;
}
.bottom-2 {
position: absolute;
bottom: 0px;
left: 0px;
height: 2px;
width: 0%;
background-color: red;
transition: width 1s ease;
}
.active {
width: 100%;
}
<div class="container">
<button onclick="activate(1)">Button 1</button>
<div id="bottom-1" class="bottom-1 transition"></div>
</div>
<div class="container">
<button onclick="activate(2)">Button 2</button>
<div id="bottom-2" class="bottom-2 transition"></div>
</div>
推荐阅读
- linux - 拼写检查包含许多文件的目录
- c++ - c++ .cpp file not found 断点调试期间的错误页面
- python - 右键单击 python tkinter 按钮后传递参数
- javascript - 将悬停消息添加到 SharePoint 中的选项
- iphone - 从 iphone 收件箱反应本机读取和解析短信
- sql - SQL 帮助 - 异常报告
- python - 我在 python 中遇到与 randint() 和 randrange() 相关的错误
- numpy - 使用 Zarr 存储 1TB 随机数据的有效方法
- python - 减去日期,只取出天数作为数字
- wordpress - 如何强制链接以保护新帖子中的内容(主要是图像)