我的按钮不会通过javascript DOM从左侧移动到右上角



我在屏幕左中角的html中有一个按钮,该按钮的样式如下:

.openbtn {
font-size: 20px;
border-radius: 0 5px 5px 0;
cursor: pointer;
position: fixed;
Top: 50%;
left: 0px;
background-color: #181A1B;
color: white;
padding: 10px 15px;
border: none;
z-index: 1;
transition: 0.5s;
}

现在,当我点击这个按钮时,我希望它转移到右上角,当我再次点击时,它应该会回到原来的位置。在Javascript中,按钮是这样处理的:

var lastState = false;
function sideButtonClicked() {
if(!lastState){
//open
lastState=true
document.getElementById("Button").style.left = "";
document.getElementById("Button").style.right = "0";
document.getElementById("Button").style.top = "0";
}
else{
//close
lastState=false
document.getElementById("Button").style.left = "0px";
document.getElementById("Button").style.right = "";
document.getElementById("Button").style.top = "50%";
}

我觉得这很棘手,因为如果我想播放右上角的按钮,当我在css上声明它时,我不会放置left属性,但由于它的初始位置在左边,我必须声明它。我尝试将它设置为",但它不起作用。我所知道的工作原理是点击按钮后按钮向上/向下移动,}

这是如何在vanillaJS中切换类的一个简单示例。然后,您只需通过CSS进行样式设置。

// Cache the DOM element for continued use
var btn = document.getElementById("btn");
// Attach event listener to button for 'click' event
btn.addEventListener("click", () =>
{
// Where we see if it has the class or not

// Is it inactive?
if (!btn.classList.contains("active"))
{
console.log("Added");
btn.classList.add("active");
} else // If it *is* currently active
{
console.log("Removed");
btn.classList.remove("active");
}
});
.btn {
padding: 1rem;
width: 200px;
transition: all 300ms ease-in-out;
}
.btn.active {
padding: 2rem;
width: 400px;
}
<button class="btn" id="btn">Click Me</button>

本质上,您使用CSS类作为不同样式的目标,而只是使用JS来打开/关闭该类。这样,您只需将CSS中的"toggle"类编辑为您想要的任何内容,代码就会一直工作。这通常是我们用于粘性导航条等的。您只需添加/删除另一个类,它就会覆盖默认样式。

最新更新