使用JavaScript随机调整CSS位置时点击黑圈无响应如何解决?
问题原因
- 代码存在JS语法错误:JS 内置数学对象名称为大写开头的
Math,小写math属于未定义变量,函数执行会直接抛出引用错误,后续逻辑无法生效 - 缺少必要的CSS定位规则:默认HTML元素的
position属性为static,该模式下top、left属性不会生效,需要给按钮设置非静态定位规则才能让位置修改生效
修复后代码
JavaScript
function myFunction1(button) { // 修正Math对象大小写 var xPosition = Math.floor(Math.random() * 101) + '%'; button.style.top = xPosition; var yPosition = Math.floor(Math.random() * 101) + '%'; button.style.left = yPosition; }
CSS
.circle { width: 100px; height: 100px; background-color: red; border-radius: 50%; /* 新增定位规则,fixed代表相对浏览器视口定位,也可以根据需求换成absolute相对父元素定位 */ position: fixed; } .black { background-color: black; }
HTML
<button type="button" class="black circle" onclick="myFunction1(this)"></button>
内容的提问来源于stack exchange,提问作者Daan Kok
相关产品推荐
相关产品推荐

