在每次onclick事件后随机定位图像(图像必须在div标签中)



所以我是非常新的(因为我确信我的代码显示:p),我必须创建包含div标记中的图像的代码。一定是这样。一旦文档被打开,图像(div)将显示在一个随机位置。每次单击图像(div)时,图像本身移动到另一个随机位置。它不会自我复制。只是动作。我有过其他"更好"的经历。但经过我所有的编辑和更改,我得到的只是左上角的图像。

我尝试了很多方法,但都失败了。显然失败了,因为代码很糟糕。我已经尝试了onclick事件等的变化…我知道很多错误是显而易见的。这不是我认为逻辑合理的例子之一,它应该起作用。这是一个"我在干什么"实例

<script>
function fpos () {
var img = document.getElementById('myImage') //is this needed at all? 
var x = Math.floor(Math.random()*600);      
var y = Math.floor(Math.random()*600);
var z = Math.floor(Math.random()*600);

}

function rmove() {    
img.style.top = x + 'px';                   
img.style.left = y + 'px';


}


</script>
</head>
<body onload="fpos"> 
<div style = position:absolute; onclick="rmove" >
<img id="myImage" src='images/iasip.jpeg'> </img>
</div>
</body>

所以,首先,不要误解我的意思,但你必须发布一些代码,向我们展示你在做什么。

也就是说,你需要用JS来做。首先定位图像元素。可以使用querySelector来命中类或id,或者只命中getElementById。

然后添加一个事件监听器,以随机坐标呈现它。这样的。

<div id="imageContainer">
<img src="your-image-source" alt="your-image-description">
</div>

<script>
// get the image container element
var imageContainer = document.getElementById("imageContainer");

// set the initial random position for the image container
imageContainer.style.left = Math.floor(Math.random() * window.innerWidth) + "px";
imageContainer.style.top = Math.floor(Math.random() * window.innerHeight) + "px";

// when the image container is clicked, set a new random position
imageContainer.addEventListener("click", function() {
imageContainer.style.left = Math.floor(Math.random() * window.innerWidth) + "px";
imageContainer.style.top = Math.floor(Math.random() * window.innerHeight) + "px";
});
</script>

既可以像示例中那样内联,也可以将其添加到脚本文件中。

这是我刚刚拼凑的一个工作示例。

基本上,您需要创建一个函数,每次通过计算高度和宽度的随机数来移动图像,然后乘以窗口的大小,以便该数字可以跨越屏幕的整个宽度/长度。

然后你可以将'px'添加到计算的末尾,以像素为单位,并将其设置为图像的lefttop属性,以使用绝对位置(坐标)将其从屏幕的左侧和顶部移动那么远。

window.onload = function() {
move()
}
function move() {
let img = document.getElementById('logo')
img.style.left = Math.floor(Math.random() * window.innerWidth) + "px"
img.style.top = Math.floor(Math.random() * window.innerHeight) + "px"
}
#logo {
height: 100px;
position: absolute;
}
<div>
<img onclick='move()' id='logo' src='https://upload.wikimedia.org/wikipedia/commons/thumb/2/24/LEGO_logo.svg/2048px-LEGO_logo.svg.png' />
</div>

别担心,试着分离出一些代码,这样我们就可以检查了。

一旦文档被打开,图像(div)将显示在a随机位置。

通过右击>检查在属性,你会发现所有的javascript属性,你可以访问一旦你选择的元素与选择器(文档。querySelector(例如)

尝试一下,我认为最简单的方法是使用Element.style.transform = "translate(x,y)"比如x.style.transform = "translate(10px, 20px)";

最新更新