简体   繁体   English

如何在每次点击时使用 position 移动元素 Javascript

[英]How to move element with position on every click Javascript

So I have a button所以我有一个按钮

        <button class="item">Button</button>

And I want it to move 100px left everytime I click on it So I did this我希望每次点击它时它向左移动 100px 所以我这样做了

 item = document.querySelector(".item") let moveItem =()=>{ item.style.position = 'absolute' item.style.left += '100px' } item.addEventListener("click", moveItem)
But it only moves one time. 但它只移动一次。 How do i move it everytime i click on it? 每次单击它时如何移动它?

Logical error in generating the position left value生成 position 左值的逻辑错误

Adding position left like item.style.left += '100px' will keeps on generating a string consisting of 100px multiple times.添加 position left like item.style.left += '100px'将多次生成由100px组成的字符串。 First time it runs, it will gives you a result 100px which you sets for the position left, next time this operation will give you a result 100px100px which is an invalid value for position left.第一次运行时,它会给你一个结果100px ,你为 position 左边设置,下一次这个操作会给你一个结果100px100px ,这是 position 左边的无效值。 So it will not update the position left property with the new value, instead it keeps the old value.因此它不会用新值更新 position left 属性,而是保留旧值。

My solution: Each time you click the button, get the current numeric value for the position left and 100 to that value.我的解决方案:每次单击按钮时,获取 position 左侧的当前数值,并将 100 减去该值。

 item = document.querySelector(".item") let moveItem =()=>{ item.style.position = 'absolute' const currentpos = item.style.left.match(/\d+/g); item.style.left = currentpos? +currentpos[0] + 100 + 'px': '100px' } item.addEventListener("click", moveItem)
 <button class="item">Button</button>

First your brackets are wrong on your moveItem function so change these to curly braces, then style.left returns null or a string so you need to parse it as an int:首先,您的moveItem function 上的括号是错误的,因此请将它们更改为大括号,然后style.left返回 null 或一个字符串,因此您需要将其解析为 int:

 const item = document.querySelector(".item") let moveItem = () => { // change bracket type item.style.position = 'absolute'; const left = item.style.left || 0; // get left if it exists or default to zero item.style.left = `${parseInt(left, 10) + 100}px`; // change the left value to an int and add 100 } item.addEventListener("click", moveItem)
 <button class="item">Button</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM