admin管理员组

文章数量:1426488

I want to change the position of the image when mouse move but the image doesn't change even if position is changed when I did console.log

var image = document.getElementById('img')

image.addEventListener('mousemove', function(e) {
  console.log(e.pageX * -1 / 12)
  var valueX = (e.pageX * -1 / 12);
  var valueY = (e.pageY * -1 / 12);
  image.style.backgroundPositionX = valueX + "px"
  image.style.backgroundPositionY = valueY + "px"
});
<header>

  <img id="img" src="" alt="">

</header>

I want to change the position of the image when mouse move but the image doesn't change even if position is changed when I did console.log

var image = document.getElementById('img')

image.addEventListener('mousemove', function(e) {
  console.log(e.pageX * -1 / 12)
  var valueX = (e.pageX * -1 / 12);
  var valueY = (e.pageY * -1 / 12);
  image.style.backgroundPositionX = valueX + "px"
  image.style.backgroundPositionY = valueY + "px"
});
<header>

  <img id="img" src="https://placehold.it/100x100" alt="">

</header>

header {
    height: 100vh;
    width: 100%;
    position: absolute;
    overflow: hidden;
}

header img {
    width: 100%;
    height: 100%;
    position: absolute;
}
Share Improve this question edited Jul 20, 2019 at 22:03 ana bel asked Jul 20, 2019 at 21:38 ana belana bel 1872 silver badges16 bronze badges 1
  • Can you please provide a working demo please or maybe include the relevant css for the img tag. Thank you. – NewToJS Commented Jul 20, 2019 at 21:44
Add a ment  | 

2 Answers 2

Reset to default 3

You need to add style="position:absolute;" to your img.

Also, you need to change backgroundPositionX to left and backgroundPositionY to top.

I'm not entirely sure this is the behavior you're going for but following the above steps will cause the image to move when the mouse moves (provided the mouse is on the image).

You almost had it. This sample code just fleshes things out a bit and moved some stuff to the CSS.

The key change was using a <div> instead of a <img>. As you were using backgroundPositionX and backgroundPositionY in the Javascript, these values are for the background image of an element and do not work with a <img>. Well, they can be used there too, but the src will hide the background unless you use a transparent image.

function mvImg(e) {
  var valueX = (e.pageX * -1 / 12);
  var valueY = (e.pageY * -1 / 12);
  this.style.backgroundPositionX = valueX + "px"
  this.style.backgroundPositionY = valueY + "px"
}
window.onload = function() {
  var im = document.getElementById("mv-img");
  if (im) {
    im.addEventListener("mousemove",mvImg,false);
  }  
}
#mv-img {
  width:100px;
  height:100px;
  background-image:url("https://via.placeholder./100/456");
  background-repeat: no-repeat;
  background-color: #192;
}
<div id="mv-img"></div>

本文标签: javascriptChange the position of an image on mousemoveStack Overflow