为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

MM们 2024-01-11 16:34:04
我有一个 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 属性,但由于它的初始位置位于左侧,所以我必须声明它。我尝试将其设置为“”,但不起作用。我知道有效的是按钮在单击按钮时向上/向下移动,}
查看完整描述

1 回答

?
HUWWW

TA贡献1874条经验 获得超12个赞

这是如何在 vanilla JS 中切换类的简单示例。然后,您只需通过 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”类编辑为您想要的任何内容,并且代码将始终有效。这通常是我们用于粘性导航栏等的方法。您只需添加/删除另一个类,它就会覆盖默认样式。



查看完整回答
反对 回复 2024-01-11
  • 1 回答
  • 0 关注
  • 26 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信