拥有动态更改的鼠标位置,我试图将其转换为宽度像素,如果鼠标位于屏幕底部,则将其设置为 0px,如果鼠标位于屏幕的顶部框架,则将其设置为 100px,这怎么可能js?也许我需要一个正则转换表达式。也许我还需要一个 if 语句?
let posY = 0.23 // received from the outer function
const el = document.querySelector(".el")
el.style.width = (posY*2 ...) + 'px', //trying to write this line, make it wider if posY > 0, more narrow if posY < 0 relatively
我想它会是这样的:
document.addEventListener('DOMContentLoaded', () => {
const viewportHeight = (window.innerHeight || document.documentElement.clientHeight);
const elBar = document.querySelector('.bar');
const elInfo = document.querySelector('.info');
window.addEventListener('mousemove', (event) => {
const width = parseInt(((viewportHeight - event.offsetY) / viewportHeight) * 100);
elBar.style.width = `${width}px`;
elInfo.innerHTML = `Width: ${width}px`;
});
});
.bar {
background: red;
display: inline-block;
}
<div class="bar"> </div>
<div class="info"></div>