我想使用jQuery每2秒随机显示一张图片。但是图像始终显示在静态位置(左上角)。我console.logged图像的属性,其左侧和顶部显示随机px。
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;
}
您需要使用样式,而不是左/上属性
style="left:10px;right:10px"
与您的摘要进行的其他调整:
<script>
添加到html)#container
放入,我做了这个position:relative
,所以position:absolute
可以工作$("#"+id)
重新查找的需要i++
,这样您就不会尝试将click附加到尚不存在的东西上(但没关系,因为它不用于重新查找新元素)$(this).remove()
必须在之后 $(this).attr("id")
-您在获取ID之前已将其删除this
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>