javascript - 为参数的条件编写 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>
错误主要是因为我不确定语法:(
解决方案
希望它对你有帮助
创建新变量时必须使用 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>
推荐阅读
- android - 反编译 APK 中显示的 Gradle.Property 值
- node.js - Angular 6 - 请求的资源上不存在“Access-Control-Allow-Origin”标头
- java - LittleProxy 操纵发送的请求和接收的响应
- python - 遍历子目录,将图片转换成pdf,然后合并pdf
- mongodb - 如何在mongodb中对象数组的第一个对象的第一个字段上应用聚合
- ios - 在谷歌登录提醒中更改应用名称的要求
- angularjs - Angular Js - [$injector:unpr] 未知提供者:nameFilterProvider <- nameFilter
- javascript - 如何使用 Javascript 显示来自 xml 的图像?
- angular - 使用动态组件加载时Angular中的循环依赖
- html - 如何在AngularJS中找到长度