css 使用一些计算点击按钮时按钮不移动

j91ykkif  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(138)

当点击按钮时,我从顶部和左侧随机分配边距给它,所以它可以移动,但它不工作。
超文本标记语言

<button id="bouncing" class="btn btn-primary">Click Me</button>

JS系统

var button = document.querySelector("button");

button.addEventListener("click", function() {
  var changeTop = (Math.random() * ($(window).height() - $("button").height()));
  var changeLeft = (Math.random() * ($(window).width() - $("button").width()));
  $("button").css("margin-top", changeTop + "px");
  $("button").css("margin-left", changeLeft + "px");
});
a9wyjsp7

a9wyjsp71#

这很好用,您可能没有在代码中包含jQuery

var button = document.querySelector("button");

button.addEventListener("click", function() {
  var changeTop = (Math.random() * ($(window).height() - $("button").height()));
  var changeLeft = (Math.random() * ($(window).width() - $("button").width()));
  $("button").css("margin-top", changeTop + "px");
  $("button").css("margin-left", changeLeft + "px");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="bouncing" class="btn btn-primary">Click Me</button>
6ie5vjzr

6ie5vjzr2#

你忘了添加jquery。通过CDN添加它或者安装它,它就可以工作了,就像这样-

var button = document.querySelector("button");

button.addEventListener("click", function() {
  var changeTop = (Math.random() * ($(window).height() - $("button").height()));
  var changeLeft = (Math.random() * ($(window).width() - $("button").width()));
  $("button").css("margin-top", changeTop + "px");
  $("button").css("margin-left", changeLeft + "px");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="bouncing" class="btn btn-primary">Click Me</button>

相关问题