首页 > 解决方案 > 为参数的条件编写 If 语句

问题描述

我有一个基本的图形用户界面,如果用户单击“移动”,那么 div(黄色矩形)会在屏幕上移动。

但是,我希望有一个基于矩形在页面上的位置的事件。例如,如果 div 位于 400px(右),则提示“嘿”,否则,移动 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>

错误主要是因为我不确定语法:(

标签: javascriptjqueryhtml

解决方案


希望它对你有帮助

创建新变量时必须使用 var (let, const)

我添加了 CONSTANTS 以便于配置,

isDivCanMoveForward为您:

矩形在页面上的位置。例如,如果 div 位于 400px(右),则提示“嘿”,否则,移动 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>


推荐阅读