提问人:bob 提问时间:10/29/2023 更新时间:10/29/2023 访问量:44
如何将鼠标垂直/水平位置转换为宽度(px) JavaScript?
How is it possible to convert mouse vertical/horizonta position to width (px) JavaScript?
问:
动态更改鼠标位置后,我正在尝试将其转换为宽度像素,如果鼠标位于屏幕底部,则为 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
答:
1赞
o q
10/29/2023
#1
我想它会是这样的:
document.addEventListener('DOMContentLoaded', () => {
const MAX_WIDTH = 100;
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) * MAX_WIDTH);
elBar.style.width = `${width}px`;
elInfo.innerHTML = `Width: ${width}px`;
});
});
.bar {
background: red;
display: inline-block;
}
<div class="bar"> </div>
<div class="info">Try to move your mouse here</div>
尝试在代码段上方的鼠标上下移动。它应该根据视口上的鼠标位置显示以像素为单位的转换大小。
评论
1赞
o q
10/29/2023
是用于存储浏览器高度的变量。还有一种以像素形式提供有关浏览器中鼠标垂直位置的信息,浏览器最顶部的值为 0,底部的值更高。既然问题是关于让它“倒置”(顶部值较高,底部值较低),那么计算应该是计算相反的。稍后,此计算结果将用作该值的“百分比”。viewportHeight
event.offsetY
MAX_WIDTH
评论
el