gpt4 book ai didi

javascript - 如何让按钮每次点击都保持移动?

转载 作者:行者123 更新时间:2023-12-01 03:20:07 28 4
gpt4 key购买 nike

我编写了这段代码,使按钮每次点击时都会向左移动..但它只移动一次并停止..请帮我找到错误

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<style>
#myBtn {
position: absolute;
}
</style>
</head>

<body>

<button type="button" id="myBtn" onclick="myFunction()">Set left position to
100 px</button>

<script>
function myFunction() {
document.getElementById("myBtn").style.left = "100px";
}
</script>

</body>

</html>

最佳答案

function myFunction() {

var currentLeft = parseInt(document.getElementById("myBtn").style.left) || 0;

document.getElementById("myBtn").style.left = currentLeft + 100 + "px";
}
#myBtn {
position: absolute;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
</head>

<body>

<button type="button" id="myBtn" onclick="myFunction()">Set left position to
100 px</button>


</body>

</html>

获取当前左侧位置,增加100并赋值给元素。

document.getElementById("myBtn").style.left = parseInt(document.getElementById("myBtn").style.left) + 100 + "px";

关于javascript - 如何让按钮每次点击都保持移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45276632/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com