jQuery使图像弹出框在随机位置不起作用

问题描述 投票:1回答:1

我想使用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;
}
javascript jquery
1个回答
0
投票

您需要使用样式,而不是左/上属性

style="left:10px;right:10px"

与您的摘要进行的其他调整:

  • 包括jquery(代码段编辑器左侧的选项将<script>添加到html)
  • 需要#container放入,我做了这个position:relative,所以position:absolute可以工作
  • 通过链接附件消除了$("#"+id)重新查找的需要
  • 在开始时放上i++,这样您就不会尝试将click附加到尚不存在的东西上(但没关系,因为它不用于重新查找新元素)
  • [$(this).remove()必须在之后 $(this).attr("id")-您在获取ID之前已将其删除
  • 在点击处理程序而不是event.target中使用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>
© www.soinside.com 2019 - 2024. All rights reserved.