当前光标位置(百分比)

Current Cursor Position in Percentages

本文关键字:百分比 位置 光标      更新时间:2024-04-02

如何以百分比形式获取当前光标位置(xy坐标)?

<script type="text/javascript">
    $(document).ready(function(){
        $(document).mousemove(function(getCurrentPos){
            var xCord = getCurrentPos.pageX;
            var yCord = getCurrentPos.pageY;
            console.log(xCord+" "+yCord);
        });
    });
</script>

我想要页面的总宽度(x坐标)的百分比来处理响应布局?

您可以放入一个jquery .width()调用,类似于:

xPercent = xCord / $( document ).width() * 100;
console.log( xPercent + "%" );

(另请注意jQuery .height()调用)

pageY将考虑浏览器标题栏的偏移量,您需要使用clientY。在下面的代码中,您将得到从0到1的xPercentyPercent(如果需要实际百分比,请乘以100)。

$(document).mousemove(function(getCurrentPos){
    var xCord = getCurrentPos.clientX;
    var yCord = getCurrentPos.clientY;
    var xPercent = xCord/window.innerWidth;
    var yPercent = yCord/window.innerHeight;
});

或者,由于您使用的是jQuery,$(window).width()$(window).height()更适合跨浏览器使用。

使用:getCurrentPos.view.outerHeight&CCD_ 10来获得实际的高度大小&宽度,然后用你已经得到的计算百分比。

我知道这是非常古老的,并且有一个公认的答案,但我想既然它出现在谷歌上,我会提供一种非Jquery的方式,尽管它可能很简单。

我制作这个CodePen是为了方便参考:https://codepen.io/DouglasGlover/pen/eYNPjwg

HTML(用于显示数字):

Position X: <span id="posX">NaN</span>%<br/>
Position Y: <span id="posY">NaN</span>%

CSS(使演示体的高度和宽度达到100%):

body {
  margin: 0;
  overflow: hidden;
  width: 100vw;
  height: 100vh;
  background: skyblue;
  font-weight: bold;
  font-family: arial;
}

Javascript(魔术):

// Container and displays
const container = document.querySelector("body");
let posXDisplay = document.getElementById("posX");
let posYDisplay = document.getElementById("posY");
// On mousemove
container.addEventListener("mousemove", (e)=> {
  // Do math
  xPercent = parseInt(e.pageX / window.innerWidth * 100);
  yPercent = parseInt(e.pageY / window.innerHeight * 100);
  // Display numbers
  posXDisplay.innerText = xPercent;
  posYDisplay.innerText = yPercent;
});