我有一段代码可以在单击该 div 时移动一个“div”,但它不起作用。
$(".shape").click(function() {
var bodyHight = document.body.clientHeight;
var bodyWidth = document.body.clientWidth;
var randomX = Math.floor((Math.random() * bodyWidth));
var randomY = Math.floor((Math.random() * bodyHeight));
$(".shape").css("left", randomX);
$(".shape").css("top", randomY);
});
和一些CSS:
.shape{
border-radius: 50px;
width: 10px;
height: 10px;
background-color: white;
position: absolute;
left: 50%;
top: 50%;
}
谁能帮帮我?
最佳答案
像这样改变:
$(document).ready(function(){
$(".shape").click(function() {
var bodyWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var bodyHight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var randomX = Math.floor((Math.random() * bodyWidth));
var randomY = Math.floor((Math.random() * bodyHight));
$(".shape").css({top: randomY, left:randomX});
});
});
.shape{
border-radius: 50px;
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="shape"></div>
关于javascript - 单击div时如何动态操作css以使div移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45124580/