javascript - 在我点击鼠标的地方创建按钮

标签 javascript dom-events

我想创建一个显示鼠标点击次数的按钮(该按钮应该出现在我点击的位置),并在 10 秒后删除该按钮。这是我尝试解决问题的代码:

<!DOCTYPE html> 
<html> 
    <head>
    </head> 
    <body>
    </body> 
    <script type ="text/javascript"> 
    counter = 1; 

    document.onclick = function(e){
        var button =document.createElement('button');

        button.style.position ="fixed";
        button.style.marginLeft= e.screenX;
        button.style.marginTop = e.screenY;
        button.label =x;
       
        document.body.appendChild(button);
        setTimeout(function() {
            document.body.removeChild(button);
        }, 1000;
    };
    </script> 
</html>

最佳答案

下面的代码将实现您想要的功能!

<html>

<head>
</head>

<body>
</body>
<script type="text/javascript">
  counter = 1;

  document.onclick = function(e) {
    var button = document.createElement('button');
    button.style.position = 'fixed';
    button.style.left = e.pageX + 'px';
    button.style.top = e.pageY + 'px';
    button.innerHTML = counter;
    counter++;

    document.body.appendChild(button);

    setTimeout(function() {
      document.body.removeChild(button);
    }, 1000);
  };
</script>

</html>

关于javascript - 在我点击鼠标的地方创建按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39311527/

相关文章:

javascript - 如何在react js初始化时将一个状态值传递给另一个状态

javascript - Angular ng-submit 调用了两次

javascript - 内容脚本未执行

javascript - HTML、Javascript : button doesn't call function

javascript - 为 JavaScript 函数提供事件参数

javascript - 第一次窗口加载或 iframe 加载会发生什么事件?

javascript - 将引号传递给 Javascript 函数内 html 元素内的 onclick 事件

javascript - webpack 中的 url-loader 配置正在从 React JS 项目中的不同路径加载图像

javascript - window.location 麻烦的 JQuery 代码

javascript - 在 Javascript 中更新多个 id