javascript 单击时按钮不移动

1l5u6lss  于 11个月前  发布在  Java
关注(0)|答案(2)|浏览(112)

我创建了一个按钮,当它被点击时必须 * 移动到一个随机位置 *。我创建了一个带有按钮的html页面,该按钮具有一个函数。该函数被调用,我创建了两个变量 heightwidth 来生成一个随机的高度和宽度。但是document.style.top属性不像预期的那样工作。请帮助我找到一个合适的解决方案。谢谢
HTML代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Move Button</title>
</head>
<body>
    
    <script src="Script.js" type="text/Javascript"> </script>
    <button id="my-button" onclick= "MoveText()" >Click me</button>

    <style>
        body {
             background-color: rgb(62, 59, 229);
             color:yellow;
             font-weight: 500;
             letter-spacing: 2;
             font-size: 35px;
             
         }
     </style>
 
    
    
</body>
</html>

字符串
JavaScript文件(Script.js):

function MoveText() {    
    const Button_select=document.getElementById('my-button')
    console.log(Button_select)

    var height=String(Math.floor(Math.random()*500))+'px'
    var width=String(Math.floor(Math.random()*900))+'px'

    Button_select.style.top = height;
    Button_select.style.left = width;

    Button_select.style.color = 'Red'
}


我还尝试了内联JavaScript,但没有工作。我还在样式部分添加了位置属性,并尝试将其设置为绝对和相对,但它没有工作。我希望按钮在单击时出现在随机位置。

gab6jxml

gab6jxml1#

这是因为你的按钮位置不正确,你需要将它固定或绝对(相对于父元素)定位,这样top/bottom/left/right css属性才能正常工作。
将HTML按钮代码更改为

<button id="my-button" style="position: fixed;" onclick= "MoveText()" >Click me</button>

字符串

w46czmvw

w46czmvw2#

将按钮的CSS位置设置为static(默认值)以外的值。

Button_select.style.position = 'fixed';

字符串

相关问题