我是Javascript的初学者,并试图创建一个使用鼠标指针推送框的简单脚本。但不幸的是,由于某种原因它不起作用,我希望你们可以帮助我。
(这个脚本非常原始,只能从左到右推动框。)
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);
答案 0 :(得分:2)
JQuery版本,但完成了与您尝试的相同
我可以通过你的脚本看到的主要问题是e.pageX == box.offsetLeft意味着它只会在pageX正好是offsetLeft时被触发。
mousemove事件不会触发每个像素,因此这种方法不起作用。最简单的方法是将鼠标移动到实际的盒子上(所以只有当用户将鼠标放在盒子上时才会触发)
其次,在框上设置left属性没有做任何事情,因为左/右边是由边距设置的:auto。将其更改为position:absolute使其实际上注意左属性。
答案 1 :(得分:1)
您需要为元素设置除position
之外的CSS static
属性,以便CSS left
属性可以正常工作。
.css-box{
position: absolute;
width : 100px;
height : 100px;
margin : auto;
background-color : blue;
}
答案 2 :(得分:1)
box.style.left
是一个字符串。在JavaScript中,如果你string + int
,int将被类型转换为字符串,你得到string + string
。例如,如果box.style.left
为10px
,则会获得:
'10px' + 1 + 'px'
int typecasted to string
'10px' + '1' + 'px'
create one string
'10px1px'
这将是box.style.left
的价值。那不是你想要的......
要解决此问题,您可以使用parseInt()
,它将字符串解析为int:
box.style.left = parseInt(box.style.left) + 1 + "px";
如果光标的X位置与box.offsetLeft
完全相同,则if仅匹配。这几乎是不可能的,我不知道你要用它做什么呢?
至少,box.style.left
第一次没有价值。您需要先将值设置为0
,然后使用该事件。
一个工作示例将是:http://jsfiddle.net/WouterJ/enLwh/(请注意我添加了position: relative;
,因为我们无法在当前位置使用left
属性)
更多提示,因为您不熟悉JS:
如果您这样做:
X = X + 12;
您可以将其缩短为:
X += 12;
答案 3 :(得分:1)
最后你最好添加一些onload而不是让脚本存在于正文中
这是一个位于页面头部的脚本,其他问题已经由其他人在这里解决了
var pushBox = function(e){
if(e.pageX >= box.offsetLeft){
box.style.left = (parseInt(box.style.left,10) + 1) + "px";
}
},box;
window.onload=function() {
box = document.getElementById("box");
document.addEventListener("mousemove" , pushBox);
}