NineQueen 2022-05-15 21:04 采纳率: 50%
浏览 20
已结题

js中如何随机更改标签的top值(语言-javascript)

如题

问题相关代码
var n = document.getElementById('not');
n.onmouseover = function(){
        var top = Math.random()*200+100;
        var right = Math.random()*300+100;
        n.style.top = top;
        n.style.right = right;
}
我想要达到的结果

鼠标移动到id为not的按钮上时,随机更改top和right值
我现在可以做到更改为指定值,但是没有办法做到随机值

已经有4年没写过前端了,最近都在搞竞赛,希望各位不吝指教

  • 写回答

1条回答 默认 最新

  • v逆水行舟v 2022-05-15 21:35
    关注

    是否解决了你说的问题?

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            html,
            body {
                height: 100%;
                margin: 0;
            }
            #not {
                position: fixed;
                top: 0;
                left: 0;
                border: 0;
                background-color: aqua;
                width: 50px;
                height: 30px;
                line-height: 30px;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <button id="not">随机</button>
    
        <script>
            const btn = document.getElementById('not');
            const maxTop = document.body.clientHeight;
            const maxLeft = document.body.clientWidth;
            function getRandomPos() {
                const randomTop = Math.floor(Math.random() * (maxTop - 50));
                const randomLeft = Math.floor(Math.random() * (maxLeft - 30));
    
                return {
                    randomLeft,
                    randomTop
                }
            }
    
            btn.onmouseenter = () => {
                const { randomLeft, randomTop } = getRandomPos();
    
                btn.style.top = randomTop + 'px';
                btn.style.left = randomLeft + 'px';
            };
        </script>
    </body>
    </html>
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 5月23日
  • 已采纳回答 5月15日
  • 创建了问题 5月15日

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?