JSFiddle - React, Tailwind, and code Playground
HTML
<div id="piyo">
X:<br>Y:
</div>
<div id="hoge">
<div id="fuga">
</div>
</div>
CSS
#hoge {
width: 90vh;
height: 90vh;
background-color: pink;
overflow: scroll;
}
#fuga {
width: 200vh;
height: 200vh;
background-color: skyblue;
}
JavaScript
const hoge = document.getElementById('hoge');
const piyo = document.getElementById('piyo');
hoge.addEventListener('scroll', listener, false);
hoge.addEventListener('click', listener, false);
function listener(e){
const Xmax = hoge.scrollWidth - hoge.clientWidth;
const Xper = scrollLeftPercent.call(hoge);
const Ymax = hoge.scrollHeight-hoge.clientHeight;
const Yper = scrollTopPercent.call(hoge);
piyo.innerHTML =
`X: ${Xper}%, ${hoge.scrollLeft}/${Xmax}` +
`<br>` +
`Y: ${Yper}%, ${hoge.scrollTop}/${Ymax}`;
}
function toRoundPercent(n1, n2){
const num = n1 / n2 * 100;
return (0 < num && num < 1) ?
1:
Math.floor(num);
}
function scrollLeftPercent(){
if( this.scrollLeft ){
const maxLeft = this.scrollWidth - this.clientWidth;
return toRoundPercent(this.scrollLeft, maxLeft);
}else{
return 0;
}
}
function scrollTopPercent(){
if( this.scrollTop ){
const maxTop = this.scrollHeight - this.clientHeight;
return toRoundPercent(this.scrollTop, maxTop);
}else{
return 0;
}
}