gpt4 book ai didi

javascript - 为参数的条件编写 If 语句

转载 作者:行者123 更新时间:2023-11-30 13:51:25 24 4
gpt4 key购买 nike

我有一个基本的图形用户界面,如果用户点击“移动”然后一个 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>

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

最佳答案

希望对你有帮助

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

我添加了 CONSTANTS 以便于配置,

isDivCanMoveForward 为您:

Where the rectangle is on the page. In example, If the div is at 400px (right) then alert "hey", else, move the 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>

关于javascript - 为参数的条件编写 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58154683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com