我的按钮没有通过 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 属性,但由于它的初始位置位于左侧,所以我必须声明它。我尝试将其设置为“”,但不起作用。我知道有效的是按钮在单击按钮时向上/向下移动,}


MM们
浏览 30回答 1
1回答

HUWWW

这是如何在 vanilla JS 中切换类的简单示例。然后,您只需通过 CSS 进行样式设置即可。// Cache the DOM element for continued usevar btn = document.getElementById("btn");// Attach event listener to button for 'click' eventbtn.addEventListener("click", () =>{&nbsp; // Where we see if it has the class or not&nbsp;&nbsp;&nbsp; // Is it inactive?&nbsp; if (!btn.classList.contains("active"))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; console.log("Added");&nbsp; &nbsp; &nbsp; btn.classList.add("active");&nbsp; &nbsp; } else // If it *is* currently active&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; console.log("Removed");&nbsp; &nbsp; &nbsp; btn.classList.remove("active");&nbsp; &nbsp; }});.btn {&nbsp; padding: 1rem;&nbsp; width: 200px;&nbsp; transition: all 300ms ease-in-out;}.btn.active {&nbsp; padding: 2rem;&nbsp; width: 400px;}<button class="btn" id="btn">Click Me</button>本质上,您使用 CSS 类作为不同样式的目标,并仅使用 JS 来打开/关闭该类。这样,您只需将 CSS 中的“toggle”类编辑为您想要的任何内容,并且代码将始终有效。这通常是我们用于粘性导航栏等的方法。您只需添加/删除另一个类,它就会覆盖默认样式。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5