【发布时间】:2023-03-28 18:40:02
【问题描述】:
我的代码在网页的中心显示了一张图片,如果点击是在图片外部或内部,则会执行 2 种不同的操作。我想在每个 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>
【问题讨论】:
-
action 1;和action 2;是什么意思?我的猜测是执行此代码时会出现 JS 错误。您还会在每次点击时不断添加越来越多的事件侦听器... -
不,如果我在没有随机位置部分的情况下运行相同的代码可以正常工作。在我使用另一种方法生成 rondom 位置之前(如下)。它有效,但并不完全正确: /* var x = Math.floor(Math.random() * (max - min) + min); var y = Math.floor(Math.random() * (max - min) + min); img.style.top = x + "px"; img.style.left = y + "px";*/
-
对不起,这是我用来改变位置的代码: var x = Math.floor(Math.random() * 400); var y = Math.floor(Math.random() * 400); img.style.top = x + "px"; img.style.left = y + "px";
标签: javascript jquery html random onclick