following is my code, I wanna stop transtion but keep its current translateY, but following code stop transition and set translateY 0, I expect a way can get current translateY when transition
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!--mobile friendly-->
<meta name="viewport" content="width=device-width, user-scalable=yes">
<style>
.it {
width: 300px;
height: 300px;
background-color: pink;
transition: transform 1s cubic-bezier(0.19, 1, 0.22, 1) 0s;
}
</style>
</head>
<body>
<div >
</div>
<script type="module">
var it = document.querySelector(".it")
setTimeout(() => {
it.style.transform = "translateY(500px)"
}, 100)
setTimeout(() => {
it.style.transform = null
}, 1000)
</script>
</body>
</html>
CodePudding user response:
I wrote a method I don't know if it will satisfy you
<style>
.it {
width: 300px;
height: 300px;
background-color: pink;
transition: transform 1s cubic-bezier(0.19, 1, 0.22, 1) 0s;
}
.it-class {
transform: translateY(500px) ;
}
</style>
</head>
<body>
<div class="it">
</div>
<button>stop</button>
<script>
var it = document.querySelector(".it")
const button = document.querySelector("button")
button.onclick = () => {
it.classList.toggle('it-class')
}
</script>
CodePudding user response:
I find solution, use getBoudingRectClient().y and window.scrollY can get element abs pos y in document;
so get parent abs_pos_y and element abs_pos_y to get current element pos y from parent top border(rel_pos_y),
cur_translateY = rel_pos_y - element.offsetTop
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!--mobile friendly-->
<meta name="viewport" content="width=device-width, user-scalable=yes">
<style>
.c {
position: relative;
border: 5px solid black;
width: 300px;
height: 300px;
}
.it {
margin-top: -200px;
width: 300px;
height: 300px;
background-color: pink;
transition: 2s cubic-bezier(0.19, 1, 0.22, 1) 0s;
}
</style>
</head>
<body>
<div >
<div >
</div>
</div>
<script type="module">
var it = document.querySelector(".it")
// offsetTop don't calc translateY, so use following get element abs pos y in document
var getPos = (e) => {
var rect = e.getBoundingClientRect()
return {
x: rect.x window.scrollX,
y: rect.y window.scrollY
}
}
setTimeout(() => {
it.style.transform = "translateY(300px)"
}, 100)
//
setTimeout(() => {
var c = document.querySelector(".c")
var cy = getPos(c).y
console.log(`cy:${cy}`)
var iy = getPos(it).y
console.log(`iy:${iy}`)
it.style.transform = `translateY(${iy - cy - it.offsetTop}px)` // iy - cy is element dist from parent top border, - it.offsetTop get translateY
}, 800)
</script>
</body>
</html>