首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过单击事件更改按钮位置?

通过单击事件更改按钮位置?
EN

Stack Overflow用户
提问于 2022-03-26 18:33:30
回答 1查看 1.1K关注 0票数 1

在它的容器的左边有一个按钮,文本在右边!当按钮位于左侧时,单击它将导致按钮移动到容器的右侧。当按钮在右边时,按钮文本向左转!当按钮位于右侧时,单击它将导致按钮移动到容器的左侧。

我试过这样做: html:

代码语言:javascript
复制
<body>
    <div class="container">
        <button id="flip-flop" onclick="moveRight()">Go Right!</button>
    </div>
</body>

js文件:

代码语言:javascript
复制
function moveRight(){
    const flip_flip_button = document.getElementById("flip-flop")
    flip_flip_button.addEventListener("click", function () {
       flip_flip_button.style.left = 400 + "px";
    });
}

css:

代码语言:javascript
复制
.container {
    position: fixed;
    top: 50%;
    left: 50%;
    width: 50%;
    background-color: gray;
    transform: translate(-50%, -50%);
}

#flip-flop{
    position: relative;
}

图像

这个代码结果,按钮是向右移动的(通过第二次单击?我也不知道为什么),但responsive.How不能,我可以移动右边的按钮,直到容器右边?

EN

回答 1

Stack Overflow用户

发布于 2022-03-26 18:48:03

这里有几个问题。

  1. 每次单击按钮时,都会添加一个单击监听器。相反,只添加一个侦听器,这将完成您想要的实际工作。
  2. 不要使用element.style,因为这会产生内联样式,人们普遍认为这是非常糟糕的实践。相反,在CSS中准备一个包含所需样式的CSS类,然后单击该类。
  3. 在这种情况下,使按钮对齐到右边的最简单方法是在按钮的父元素上设置text-align: right

代码语言:javascript
复制
document
  .getElementById('flip-flop')
  .addEventListener("click", function() {
    this.parentNode.classList.toggle('right');
  });
代码语言:javascript
复制
.container {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 50%;
  background-color: gray;
  transform: translate(-50%, -50%);
}

#flip-flop {
  position: relative;
}

.right {
  text-align: right;
}

#flip-flop::after {
  content: " right!";
}

.right #flip-flop::after {
  content: " left!";
}
代码语言:javascript
复制
<div class="container">
  <button id="flip-flop">Go</button>
</div>

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71630784

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档