TypeError:试图分配给只读属性-Vanilla Javascript鼠标位置



我的预期结果是,根据对x轴鼠标位置的计算,图像在容器内移动。这就是为什么Xratio的范围从-1到1。

我不确定这里的只读属性是什么?我使用CCD_ 2;数字";。

我还使用了CCD_ 3和锯";函数";。

这可能是我不理解的一个简单的分配错误吗?

const bxImg = document.querySelector('.bx-pic');
document.addEventListener('mousemove', (e) => {
const xRatio = (e.clientX / window.innerWidth) * 2 - 1;
console.log(typeof xRatio);
const xRatioEased = 0;
if (xRatio >= 0) {
xRatioEased = easeOutExpo(xRatio);
} else {
xRatioEased = easeOutExpo(-xRatio * -1)
}
bxImg.style.transform = `scale(1.2) translate3D(${-xRatioEased * 10}px, ${0}, ${0})`;
})
function easeOutExpo(n) {
if (n === 1) {
return 1;
} else {
return 1 - Math.pow(2, -10 * n);
}
}
console.log(typeof easeOutExpo);
html, body {
width: 100%;
height: 100%;
}
body {
background-color: #FDFDFD;
}
img {
width: 100%;
height: 100%;
object-fit: cover;
}
.bx-wp {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
overflow: hidden;
width: 350px;
height: 350px;
outline: 30px solid royalblue;
}
.bx {
position: relative;
transform: scale(1.2);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="bx-wp">
<img src="https://images.unsplash.com/photo-1641113994135-a9f230b1f9b0?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2670&q=80" alt="A Mountain" class="bx bx-pic">
</div>
<script src="script.js"></script>
</body>
</html>

您已将xRatioEased声明为const,因此只能在初始化时进行设置。用let xRatioEased替换const xRatioEased,它应该全部工作。

xRatioEased是一个常数。常量只能在初始化时更改。如果将xRatioEased声明为变量(使用letvar(,则可以解决此问题。

如果你想了解更多关于常数以及何时使用它们,你可以转到这个链接

最新更新