<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100vw;
height: 100vh;
border: 1px solid black;
text-align: center;
}
</style>
</head>
<body>
<p>Click in the div element below to get the x (horizontal) and y (vertical) coordinates of the mouse pointer, when it is clicked.</p>
<div onmousemove="showCoords(event)"><p id="demo"></p></div>
<p><strong>Tip:</strong> Try to click different places in the div.</p>
<script>
function showCoords(event) {
var cX = event.clientX;
var sX = event.screenX;
var cY = event.clientY;
var sY = event.screenY;
var coords1 = "client - X: " + cX + ", Y coords: " + cY;
var coords2 = "screen - X: " + sX + ", Y coords: " + sY;
document.getElementById("demo").innerHTML = coords1 + "<br>" + coords2;
console.log(cX * 0.5);
if(cX < 0.5 * cX){
document.getElementById("demo").style.color = "red";
}
/*else if(cX > cX * 0.5 ){
document.getElementById("demo").style.color = "yellow";
}*/
else{
document.getElementById("demo").style.color = "black";
}
}
</script>
</body>
</html>
您好,我已经附上了我一直在通过W3schools工作的给定示例。我可以将cX记录到屏幕上,将其除以2。然而,当我尝试在参数中使用它时,它将无法工作。有没有其他人遇到过类似问题或者我在标记方面犯了致命错误?请告诉我。如果我发现解决方案肯定会在这里发布。谢谢。
if(cX < 0.5 * cX){
这总是false
,你可能意味着cX < 0.5 * document.body.clientWidth
。