我的代码在网页的中心显示图片,如果点击是在图片的外部或内部,则会执行2种不同的操作。我想在每个onclick()事件中随机更改图像的位置(不管点击是在还是在外),同时保持页面初始大小。Onclick()事件:图片的随机出现
这两个操作都正确完成,但图像不会更改位置。有人能告诉我我应该改变什么吗?
<html>
<head>
<title>random position</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">
$(window).height();
$(window).width();
</script>
<body>
<style>
#myImage { position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin:auto; }
</style>
<script>
function moveImg() {
var img = document.getElementById("myImage");
var width = $(img).width();
var height = $(img).height();
document.addEventListener("click", function(e) {
var offset = $(img).offset();
if (e.target === img) {
action 1;
}
else {
action 2;
}
// GENERATE RANDOM LOCATION IN BOTH CASES
img.offset.left = Math.floor(Math.random() * (window.width()- 0) + 0);
img.offset.top = Math.floor(Math.random() * (window.height()- 0) + 0);
}, false);
}
</script>
<img id="myImage" src="img.gif" onclick="moveImg()">
</body>
</html>
“行动1”和“行动2”是什么意思?我的猜测是当你执行这段代码时你会得到一个JS错误。您还不断添加越来越多的事件侦听器,每次点击... –
不,如果我运行相同的代码没有随机位置部分是行得通的。在我用另一种方法产生rondom posion之前(下)。它工作,但它不完全正确:/ * var x = Math.floor(Math.random()*(max - min)+ min);数学式(Math.random()*(max-min)+ min); img.style.top = x +“px”; img.style.left = y +“px”; */ – Gigi
对不起,这里是我用来改变位置的代码:var x = Math.floor(Math.random()* 400); var y = Math.floor(Math.random()* 400); img.style.top = x +“px”; img.style.left = y +“px”; – Gigi