如何动态操作 CSS 以使 div 在单击 div 时移动?



我有一段代码,当单击该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 片段第 2 行的 "bodyHight" 是一个拼写错误。

更重要的是,在大多数浏览器(例如Chrome(中,元素的默认高度取决于其内部元素。但是,这里您使用绝对定位,这意味着所有都不在 DOM 流中,这最终导致身体的高度为 0。所以div.shape只能在顶部1个水平像素线上水平移动。

最新更新