가능한 중복은 :
Why is this not working ? pushing a box using mouse pointer이 자바 스크립트 스크립트의 문제점은 무엇입니까?
이 마우스 포인터를 사용하여 상자를 밀어 스크립트이며, 상자가 왼쪽에서 밀어 경우에만 작동합니다.
마우스 포인터의 위치를 가져 와서 왼쪽으로 쓰는지 쓸지를 결정했습니다.
여기까지의 작업은 example입니다.
하는 index.js
<html>
<head>
<title>Chase the box</title>
<style>
body {
}
.css-box{
position: absolute ;
top:20px;
width : 100px;
height : 100px;
background-color : blue;
}
.css-textbox{
margin-top: 500px;
}
</style>
</head>
<body>
<div id="box" class="css-box"></div>
<div class="css-textbox">
<p>All : <input id="allTextbox" type="text"></input></p>
<p>Left : <input id="leftTextbox" type="text"></input></p>
<p>Right : <input id="rightTextbox" type="text"></input></p>
<p>e.pageX(Left) : <input id="pageXTextbox" type="text"></input></p>
<p>e.pageX(Right) : <input id="pageXRightTextbox" type="text"></input></p>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
script.js
var box = document.getElementById("box");
var allTextbox = document.getElementById("allTextbox");
var leftTextbox = document.getElementById("leftTextbox");
var rightTextbox = document.getElementById("rightTextbox");
var pageXTextbox = document.getElementById("pageXTextbox");
var PageXRightTextbox = document.getElementById("pageXRightTextbox");
Object.prototype.offsetRight = null;
var arr = [];
var pushBox = function(e){
var pageXRight = window.innerWidth - e.pageX;
box.offsetRight = window.innerWidth - (box.offsetWidth + box.offsetLeft);
if(arr.length < 2){
arr.push(e.pageX);
} else {
if(arr[0] < arr[1]){
if(e.pageX >= box.offsetLeft){
box.style.left = e.pageX + "px";
}
} else if(arr[0] > arr[1]){
if(pageXRight >= box.offsetRight){
box.style.right = pageXRight + "px";
}
}
arr.shift(arr[0] , arr[1]);
}
allTextbox.value = window.innerWidth;
leftTextbox.value = box.offsetLeft;
rightTextbox.value = box.offsetRight;
pageXTextbox.value = e.pageX;
pageXRightTextbox.value = pageXRight;
}
document.addEventListener("mousemove" , pushBox);
'Object.prototype'을 수정하는 것은 *** BAD ***입니다. ** B A D **. 예를 들어 jQuery와'obj.hasOwnProperty (key)'검사를 사용하지 않는'for (var obj in obj)'반복을 중단합니다 (환경이 정상이라고 가정 할 때 일반 객체를 반복 할 때 필요하지는 않습니다) – ThiefMaster
어떻게 생깁니 까? 네가 물었던 지난 두 가지 질문과 다른 점은 무엇입니까? http://stackoverflow.com/questions/11601419/trying-to-write-a-script-to-push-a-box-using-mouse-pointer-in-javascript 및 http://stackoverflow.com/questions/ 11594680/why-this-not-push-a-box-using-mouse-pointer – j08691
@Rafael, 이런 식으로 어딘가에 더하기 기호가 필요하다고 생각합니다. 'var pageXLeft = window.innerWidth + e.pageX ; ' –