我试图根据鼠标的x和y坐标制作一个非常简单的幻灯片。目前,我在js中使用像素-从代码中可以看到,当鼠标悬停在某个点上时,每个元素的显示都会更新。有没有一种方法可以在javascript中使用百分比而不是px?因此,无论屏幕的宽度和高度如何,图像都显示在同一点(例如,如果鼠标在屏幕上的位置为25%,请更改显示方式,而不是一定数量的像素)。这是我的代码:

var mouseX;
var mouseY;

var image1 = document.getElementsByClassName('test')[0];
var image2 = document.getElementsByClassName('test2')[0];

// create variables for percentages of screen?

image1.style.display = "block";
image2.style.display = "none";


function init(){

    document.onmousemove = function(e){
    mouseX = e.screenX;
    mouseY = e.screenY;
    console.log(mouseX, mouseY);
        if (mouseX <= 400) {
            image1.style.display = "none";
            image2.style.display = "block";
        }
        else if (mouseX => 800) {
            image2.style.display = "none";
            image1.style.display = "block";
        }
       //will add more of the same here
    }
}

最佳答案

您可以进行简单的数学运算以获得屏幕尺寸。

您应以window.innerWidth开头,以window.innerHeight开头。

如果您知道两个按钮都是屏幕宽度的50%,则将总数除以2。

if (mouseX < window.innerWidth / 2) {
    // Do stuff for left button
} else {
    // Do stuff for right button
}

07-24 09:43
查看更多