确保在将其分配为新职位时添加“px”。
您正在计算过程中添加它们。这就搞砸了比较。ie:
ballBorderLeft < 0
成为
'-10px' < 0
而不是
-10 < 0
将字符串与数值进行比较。
var ball = document.getElementById('ball');
var field = document.getElementById('field');
function getClick() {
var fieldCoords = this.getBoundingClientRect();
var fieldBorderLeft = fieldCoords.left + field.clientLeft;
var fieldBorderTop = fieldCoords.top + field.clientTop;
var ballBorderLeft = event.clientX - fieldBorderLeft - ball.clientWidth / 2;
var ballBorderTop = event.clientY - fieldBorderTop - ball.clientHeight / 2;
if (ballBorderLeft < 0) ballBorderLeft = 0;
if (ballBorderTop < 0) ballBorderTop = 0;
if (ballBorderLeft + ball.clientWidth > field.clientWidth) {
ballBorderLeft = field.clientWidth - ball.clientWidth;
}
if (ballBorderTop + ball.clientHeight > field.clientHeight) {
ballBorderTop = field.clientHeight - ball.clientHeight;
}
ball.style.top = ballBorderTop + 'px';
ball.style.left = ballBorderLeft + 'px';
}
field.addEventListener('click', getClick);
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
#field {
width: 200px;
height: 150px;
border: 10px groove black;
background-color: #00FF00;
position: relative;
overflow: hidden;
cursor: pointer;
user-select: none;
}
#ball {
position: absolute;
left: 0;
top: 0;
width: 40px;
height: 40px;
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: all 1s;
-ms-transition: all 1s;
transition: all 0.5s;
user-select: none;
-webkit-user-drag: none;
-ms-user-drag: none;
-moz-user-drag: none;
user-drag: none;
}
</style>
</head>
<body>
<div id="field">
<img src="https://js.cx/clipart/ball.svg" id="ball" style="left: 140px; top: 39px;"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
</div>
<script>
</script>
</body>
</html>
作为旁注,
if (ballBorderTop < 0) ballBorderLeft = 0;
可能正在设置
ballBorderTop
当你这样做的时候,加上
user-select: none;
上
#field
css规则,用于禁用文本选择。
的Idem
user-drag: none;
关于
#ball