Home > Blockchain >  Why is the attribute style not being added to the img?
Why is the attribute style not being added to the img?

Time:12-23

<div id="field">
  <img src="https://ru.js.cx/clipart/ball.svg" id="ball">
</div>
function moveBall(event){
    let x = event.clientX;
    let y = event.clientY;
    let ball = document.getElementById('ball');
    ball.style.left = x
    ball.style.top = y
}

let field = document.getElementById('field');
field.onclick = moveBall

I was expecting a style attribute with value left=... to be added to the <img> tag. It is works with <div> but not with <img>.

CodePudding user response:

There are two issues. First, x and y will need units. Second, you need to define a position for the ball, e.g. relative:

function moveBall(event) {
  let x = event.clientX;
  let y = event.clientY;
  let ball = document.getElementById('ball');
  ball.style.left = x   'px';
  ball.style.top = y   'px';
}

let field = document.getElementById('field');
field.onclick = moveBall
#ball {
  position: relative;
}
<div id="field">
  <img src="https://ru.js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</div>

CodePudding user response:

Please add this css code.

#field img {
    position: absolute;
    z-index: 1
}

#field {
  height: 100vh;
}

Also change the javascript code like this.

ball.style.left = x   'px'
ball.style.top = y    'px'

Full code (This is working well)

html

<div id="field">
  <img src="https://ru.js.cx/clipart/ball.svg" id="ball">
</div>

CSS

#field img {
    position: absolute;
    z-index: 1
}

#field {
  height: 100vh;
}

Javascript

function moveBall(event){
    let x = event.clientX;
    let y = event.clientY;
    let ball = document.getElementById('ball');
    ball.style.left = x   'px'
    ball.style.top = y    'px'
}

let field = document.getElementById('field');
field.onclick = moveBall
  • Related