为什么这不起作用?用鼠标指针推一个盒子 [英] Why is this not working ? pushing a box using mouse pointer
问题描述
我是Javascript的初学者,并试图创建一个使用鼠标指针推送框的简单脚本。但不幸的是,由于某些原因它不起作用,我希望你们可以帮助我。
I'm a beginner in Javascript, and trying to make a simple script that pushes a box using the mouse pointer. But unfortunately it isn't working for some reason, i hope you guys can help me out.
(这个剧本非常原始,只能从左边推开盒子。现在)。
(this script is really primitive, only pushes the box from the left till now).
index.html:
<html>
<head>
<title>Chase the box</title>
<style>
body {
}
.css-box{
width : 100px;
height : 100px;
margin : auto;
background-color : blue;
}
</style>
</head>
<body>
<div id="box" class="css-box"></div>
<script type="text/javascript" src="script.js"></script>
</body>
script.js:
var box = document.getElementById("box");
var pushBox = function(e){
if(e.pageX == box.offsetLeft){
box.style.left = box.style.left + 1 + "px";
}
};
document.addEventListener("mousemove" , pushBox);
推荐答案
box.style.left
是一个字符串。在JavaScript中,如果你执行 string + int
,int将被类型转换为字符串,你得到 string + string
。例如,如果 box.style.left
是 10px
,你会得到:
box.style.left
is a string. And in JavaScript if you do string + int
the int will be type casted to a string and you get string + string
. For instance, if box.style.left
is 10px
you get:
'10px' + 1 + 'px'
int typecasted to string
'10px' + '1' + 'px'
create one string
'10px1px'
这将是<$ c $的值C> box.style.left 。那不是你想要的...
And that will be the value of box.style.left
. That isn't what you want...
要解决这个问题,你可以使用 parseInt()
,它解析字符串转换为int:
To solve this you can use parseInt()
, which parses a string into an int:
box.style.left = parseInt(box.style.left) + 1 + "px";
当光标的X位置与<$完全相同时,你的if只匹配C $ C> box.offsetLeft 。这几乎是不可能的,我不知道你要用它做什么呢?
And your if is only matching when the X position of the cursor is exactly the same pixel as box.offsetLeft
. That's almost impossible, I don't know what you are trying to do with that if?
至少, box.style.left
第一次没有价值。您需要首先将值设置为 0
,然后使用该事件。
At least, box.style.left
has no value the first time. You need to set the value at first to 0
and then use the event.
一个工作示例将是: http://jsfiddle.net/WouterJ/enLwh/ (请注意我添加了 position:relative;
因为我们无法在当前位置使用 left
属性)
A working example will be: http://jsfiddle.net/WouterJ/enLwh/ (please note that I have added position: relative;
because we can't use the left
property on the current position)
更多提示,因为你是JS新手:
Some more tips, since you are new to JS:
-
如果您这样做:
If you do something like this:
X = X + 12;
您可以将其缩短为:
X + = 12;
这篇关于为什么这不起作用?用鼠标指针推一个盒子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!