Мячик выходит за границу =(
Создал скрипт, который передвигает мячик в центр, затем в правый край, а после в точку старта. Но почему мячик выходит за границу правого края? Ведь clientWidth по идее должен покрывать всю область элемента кроме границ и полосы прокрутки.
let a = document.querySelector('#block');
let b = document.querySelector('#ball');
setInterval(function(){
b.style.marginLeft = Math.round(a.clientWidth / 2 - b.offsetWidth / 2 ) + 'px';
b.style.marginTop = Math.round(a.clientHeight / 2 - b.offsetHeight / 2) + 'px';
setTimeout(()=> b.style.marginLeft = a.clientWidth + 'px',1000)
setTimeout(() =>b.style.marginLeft = '', 2000);
},3200)
#block{
background: orange;
transition: all 2s;
border: 8px solid black;
}
#ball{
width: 80px;
height: 80px;
transition: all 1s;
}
<div id ="block">
<img id = "ball" src = "https://i.ibb.co/7jmdxFQ/23.png">
</div>
Ответы (1 шт):
Автор решения: kotleni
→ Ссылка
let a = document.querySelector('#block');
let b = document.querySelector('#ball');
window.onload = function() {
setInterval(function() {
b.style.marginLeft = Math.round(a.clientWidth / 2 - b.offsetWidth / 2 ) + 'px';
b.style.marginTop = Math.round(a.clientHeight / 2 - b.offsetHeight / 2) + 'px';
setTimeout(() => b.style.marginLeft = (a.clientWidth - b.clientWidth) + 'px', 1000);
setTimeout(() => b.style.marginLeft = '', 2000);
}, 3200)
}
#block {
background: orange;
transition: all 2s;
border: 8px solid black;
}
#ball {
width: 80px;
height: 80px;
transition: all 1s;
}
<div id="block">
<img id="ball" src="https://i.ibb.co/7jmdxFQ/23.png">
</div>