JavaScript 生成随机位置按钮,点击显示不同图片
<!DOCTYPE html>
<html>
<head>
<style>
.button {
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<script>
function getRandomPosition() {
var x = Math.floor(Math.random() * window.innerWidth);
var y = Math.floor(Math.random() * window.innerHeight);
return [x, y];
}
<pre><code> function createButton() {
var button = document.createElement('button');
button.className = 'button';
button.onclick = function() {
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];
var randomIndex = Math.floor(Math.random() * images.length);
var image = new Image();
image.src = images[randomIndex];
document.body.appendChild(image);
}
return button;
}
window.onload = function() {
for (var i = 0; i < 5; i++) {
var button = createButton();
var position = getRandomPosition();
button.style.top = position[1] + 'px';
button.style.left = position[0] + 'px';
document.body.appendChild(button);
}
}
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/ph7K 著作权归作者所有。请勿转载和采集!