移动图像时,更改$(img).offset()onclick()

时间:2017-03-29 12:36:27

标签: javascript jquery html image onclick

我有一个图像,当我点击它时会随机改变位置。我想播放三种可能的不同声音之一,具体取决于点击是否为:

    图片
  • 距图像50px
  • 离图像超过50px。

为此,我需要保存图像的坐标,以便每次移动图像时更新它们。我有这段代码:

function move() {
  var audio = document.getElementById("audio");
  var img = document.getElementById("myImage");

  //FIND CENTER OF IMAGE 
  var offset = $(img).offset();
  var width = $(img).width();
  var height = $(img).height();

  // PLAY DIFFERENT SOUND
  document.addEventListener("click", function(e) {
    if (e.target === img) {
      audio.src = "sound1.mp3";
      audio.play();
    } else if (e.clientX < (offset.left - 50) || e.clientX > (offset.left + width + 50) || e.clientY < (offset.top - 50) || e.clientY > (offset.top + height + 50)) {
      audio.src = "sound2.mp3";
      audio.play();
    } else {
      audio.src = "sound3.mp3";
      audio.play();
    }
    // GENERATE RANDOM LOCATION
    // Fix this part
    var x = Math.floor(Math.random() * 400);
    var y = Math.floor(Math.random() * 400);

    img.style.top = x + "px";
    img.style.left = y + "px";
    img.style.bottom = x - "px";
    img.style.right = y - "px";
  }, false);
}

更新图像坐标时必须犯一些小错误。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

看来,每次点击都会缓存变量offset,请尝试将分配移至点击处理程序。还从移动函数中提取事件侦听器以避免内存泄漏。在您的情况下,每次触发move函数时,都会附加一个新的事件侦听器。确保您的<img id="myImage" /> position fixedabsolute设置为相对元素。如果您使用相对元素,则必须将$window更改为相对元素才能获得正确的大小。

  var $audio = $('#audio');
  var $img = $("#myImage");
  var $window = $(window);

  var width = $img.width();
  var height = $img.height();
  var maxX = $window.width() - width;
  var maxY = $window.height() - height;
  
  function move() {
    //Get a new position, use modulo operation to get x from range (0, windowWidth - imageWidth) and y from range (0, windowHeight - imageHeight)
    var x = Math.floor(Math.random() * 10000) % maxX;
    var y = Math.floor(Math.random() * 10000) % maxY;

    $img.css('left', x + 'px');
    $img.css('top', y + 'px');
  }

  document.addEventListener("click", function(e) {
    //get the img offset
    var offset = $img.offset();
    if (e.target === $img[0]) {
      audio.src = "sound1.mp3";
      audio.play();
    } else if (e.clientX < (offset.left - 50) || e.clientX > (offset.left + width + 50) || e.clientY < (offset.top - 50) || e.clientY > (offset.top + height + 50)) {
      audio.src = "sound2.mp3";
      audio.play();
    } else {
      audio.src = "sound3.mp3";
      audio.play();
    }
    
    move();
  }, false);