我正在尝试制作一个聊天应用程序,只需按一下按钮,您就可以看到消息的时间戳滑入。
我的时间戳总是占用 200px 的大小,而另一个占用其余的大小。
我们将 div1 称为时间戳 (200px),将 div2 称为消息 (占用剩余空间)。
我尝试在第一个 div1 上使用翻译并移动,很快意识到 div2 不会自动调整大小:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
*{
padding: 0px;
margin: 0px;
box-sizing: border-box;
}
.chat-container {
display: flex;
height: 50vh;
width: 50vw;
background-color: #f0f0f0;
}
#div1 {
background-color: #0004ff;
height: 100%;
width: 200px;
text-align: center;
position: relative;
left:-200px;
transition: left 1s;
}
#div2 {
background-color: #ff0000;
height: 100%;
text-align: center;
width: calc(100% - 200px); /* 100% - 200px or auto would work*/
}
</style>
</head>
<body>
<div class="chat-container">
<div id="div1">
<p>div1</p>
</div>
<div id="div2">
<p>div2</p>
</div>
</div>
<button id="button">animation</button>
<script>
let actived = false;
document.getElementById("button").addEventListener("click", function() {
const div1 = document.getElementById("div1");
const div2 = document.getElementById("div2");
div1.style.left = actived ? "-200px" : "0px";
actived = !actived;
});
</script>
</body>
</html>
因此我尝试调整 div2 的大小,但这样做之后calc(100% - 200px)
大小却不一样了!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
*{
padding: 0px;
margin: 0px;
box-sizing: border-box;
}
.chat-container {
display: flex;
height: 50vh;
width: 50vw;
background-color: #f0f0f0;
overflow: hidden;
}
#div1 {
background-color: #0004ff;
height: 100%;
width: 200px;
text-align: center;
position: relative;
left:-200px;
transition: left 1s;
}
#div2 {
background-color: #ff0000;
height: 100%;
text-align: center;
width: calc(100% - 200px); /* 100% - 200px or auto would work*/
position: relative;
transition: width 1s;
}
</style>
</head>
<body>
<div class="chat-container">
<div id="div1">
<p>div1</p>
</div>
<div id="div2">
<p>div2</p>
</div>
</div>
<button id="button">animation</button>
<script>
let actived = false;
document.getElementById("button").addEventListener("click", function() {
const div1 = document.getElementById("div1");
const div2 = document.getElementById("div2");
div1.style.left = actived ? "-200px" : "0px";
div2.style.width = actived ? "100%" : "calc(100% - 200px)";
actived = !actived;
});
</script>
</body>
</html>
100%
父元素减去 div1 的大小怎么会不是剩余的大小呢?我好困惑啊。
请告诉我应该使用什么方法以及为什么100% - 200px
不对齐。