如何将鼠标垂直/水平位置转换为宽度(px)JavaScript?

问题描述 投票:0回答:1

拥有动态更改的鼠标位置,我试图将其转换为宽度像素,如果鼠标位于屏幕底部,则将其设置为 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 

javascript jquery css if-statement mousemove
1个回答
0
投票

我想它会是这样的:

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">&nbsp;</div>
<div class="info"></div>

© www.soinside.com 2019 - 2024. All rights reserved.