問題

我有一個基本的圖形使用者介面,如果使用者單擊“移動” 然後一個div(黃色矩形)在螢幕上移動.

但是,我希望有一個基於矩形在頁面上的事件.例如,如果div在400px(右),則警告“hey”,否則,移動div.

 here is the moving div

<html>
<head>
    <title>Move Div</title>
    
    <script language ="javascript">
        <!--
            function MoveDiv()
            {
                div = document.getElementById("myDiv");
                
                
                div.style.left = parseInt(div.style.left) + 100 + "px";
            }
        //-->
    </script>
</head>
<body>
    <input type="button" value="Move Div" onclick="MoveDiv()" />
    <div id="myDiv" style="border: 10px solid black; background-color: Yellow; width: 100px; height: 30px; position: absolute; top: 1px; left: 100px;"></div>
</body>
</html> 

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
here is the moving div

<html>
<head>
    <title>Move Div</title>
    
    <script language ="javascript">
        <!--
            function MoveDiv(){
           if ($('#myDiv').css == marginTop: '-=15px' ) {
                div = document.getElementById("myDiv");
                
                
                div.style.left =  parseInt(div.style.left) + 100 + "px";
            }}
        //-->
    </script>
</head>
<body>
    <input type="button" value="Move Div" onclick="MoveDiv()" />
    <div id="myDiv" style="border: 10px solid black; background-color: Yellow; width: 100px; height: 30px; position: absolute; top: 1px; left: 100px;"></div>
</body>
</html> 

錯誤主要是因為我不確定語法:(

  最佳答案

希望它的幫助你

建立新變數時必須使用var(let,const)

我添加了CONSTANTS以便於配置,

isDivCanMoveForward for your:

在頁面上的矩形.例如,如果div在400px(右),則警告“hey”,否則,移動div.

 var MAX_POSITION_OF_DIV_NODE = 400;
var STEP_OF_DIV_NODE = 100;

var div = document.getElementById("myDiv");

var currentPositionOfDivNode = parseInt(div.style.left, 10);

function MoveDiv() {
  currentPositionOfDivNode += STEP_OF_DIV_NODE; // increment

  if (!isDivCanMoveForward()) {
    return; // stop functinon when div have max position
  }

  div.style.left = currentPositionOfDivNode + "px";
}

function isDivCanMoveForward() {
  if (currentPositionOfDivNode > MAX_POSITION_OF_DIV_NODE) {
    currentPositionOfDivNode = MAX_POSITION_OF_DIV_NODE // set max of value

    alert('hey')// user message

    return false;
  }

  return true;
} 
 <html>
  <head>
      <title>Move Div</title>
  </head>
  <body>
      <input type="button" value="Move Div" onclick="MoveDiv()" />
      <div id="myDiv" style="border: 10px solid black; background-color: Yellow; width: 100px; height: 30px; position: absolute; top: 1px; left: 100px;"></div>

  </body>
</html> 

  相同標籤的其他問題

javascriptjqueryhtml