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

标签 javascript jquery

我想使用 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/

相关文章:

javascript - 一切正常时,带有 jQ​​uery 的 Ajax 返回错误

javascript - 如何修复 Appcelerator 的 "Navigation Controller"以使用 TabGroup 作为基本窗口?

javascript - 当一个打开时折叠关闭另一个 jQuery

jquery - 如何让 TwentyTwenty.js 图片居中?

javascript - JQuery 函数不适用于初始触发器

javascript - 仅在某些计算机上解决 IE8/Superfish 问题的故障排除帮助

javascript - 将触发器中的 href 作为另一个元素的背景图片

javascript - 将值附加到 JQuery 中的输入字段

jquery - 如何将 portlet 包装在 div 中

javascript - 如何使用 jQuery 对页面文本中的某个字符串执行某些操作?