我想使用 jQuery 使图像每 2 秒随机显示一次。但图像始终显示在静态位置(左上角)。我控制台记录了图像的属性,其左侧和顶部显示随机像素。
let score = 0;
let id = 0;
$(document).ready(function () {
setInterval(setImage, 2000);
});
function setImage() {
$("#container").append(
`<img src='images/virus.gif' id='${id}' width='75px' position='absolute' class='virus' left=${randomLeft()} top=${randomTop()}/>`
);
$("#" + id)
.slideUp(0)
.fadeIn(1000);
id++;
$("#" + id).on("click", function (event) {
$(event.target).remove();
score++;
console.log($(event.target).attr("id"), score);
});
}
function randomTop() {
let height = $(window).height();
let randomHeight = Math.floor(Math.random() * (height - 75)) + "px";
return randomHeight;
}
function randomLeft() {
let width = $(window).width();
let randomLeft = Math.floor(Math.random() * (width - 75)) + "px";
return randomLeft;
}
最佳答案
您需要使用样式而不是 left/top 属性
style="left:10px;right:10px"
对您的代码片段进行一些其他调整:
- 包含 jquery(代码片段编辑器左侧的选项将
<script>
添加到 html) - 需要
#container
为了把它们放进去,我做了这个position:relative
所以position:absolute
会起作用的 - 不再需要
$("#"+id)
通过链接追加重新查找 - 输入
i++
在开头,这样您就不会尝试将点击附加到尚不存在的内容(但并不重要,因为不用于重新查找新元素) -
$(this).remove()
必须在$(this).attr("id")
之后 - 您在获取其 ID 之前将其删除 - 已使用
this
在点击处理程序而不是 event.target 内 - 会更好如
data-id=${++id}
而不是使用数字 ID,但这是一个小变化(未进行)
更新的代码片段:
let score = 0;
let id = 0;
$(document).ready(function() {
setInterval(setImage, 2000);
});
function setImage() {
var img = $(`<img src='images/img4.jpg' id='${++id}' class='virus' style='left:${randomLeft()};top:${randomTop()}' />`);
img.appendTo("#container")
.slideUp(0)
.fadeIn(1000)
.on("click", function() {
score++;
console.log($(this).attr("id"), score);
$(this).remove();
});
}
function randomTop() {
let height = $(window).height();
let randomHeight = Math.floor(Math.random() * (height - 75)) + "px";
return randomHeight;
}
function randomLeft() {
let width = $(window).width();
let randomLeft = Math.floor(Math.random() * (width - 75)) + "px";
return randomLeft;
}
#container {
position: relative;
height: 100%;
width: 100%;
}
.virus {
border: 1px solid red;
position: absolute;
width: 75px;
height: 20px;
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='container'></div>
关于javascript - jQuery 使图像弹出在随机位置不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61763234/