如何为参数条件编写If语句?解决GUI中Div位置触发事件语法问题
Fixing the Div Movement with Position-Based Alert
Hey there! Let's get your code working so that the alert pops up when the yellow div reaches left: 400px. First, let's break down what was off with your previous attempt:
- Your conditional check had invalid JavaScript syntax (
if ($('#myDiv').css == marginTop: '-=15px' )doesn’t make sense here—css()is a jQuery method, not a property, and the condition didn’t relate to checking the div’s left position at all. - You mixed unrelated margin logic with the core div movement code, which broke the basic functionality.
Corrected Implementation (Native JavaScript Version)
This uses plain JS (no jQuery) matching your original approach:
<html> <head> <title>Move Div</title> <script> function MoveDiv() { // Grab the div element const div = document.getElementById("myDiv"); // Convert current left position from "100px" to a numeric value let currentLeft = parseInt(div.style.left); // Calculate the new left position const newLeft = currentLeft + 100; // Update the div's position on the page div.style.left = newLeft + "px"; // Check if we've hit the 400px mark if (newLeft === 400) { alert("hey"); } } </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>
jQuery Version (Since You Included jQuery)
If you prefer cleaner DOM handling with jQuery, here's a tailored version:
<html> <head> <title>Move Div</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> function MoveDiv() { // Cache the jQuery div object for efficiency const $div = $("#myDiv"); // Get the current left position (jQuery handles parsing the number) let currentLeft = parseInt($div.css("left")); // Calculate the new position const newLeft = currentLeft + 100; // Update the div's left position $div.css("left", newLeft + "px"); // Trigger the alert when we reach 400px left if (newLeft === 400) { alert("hey"); } } </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>
How It Works
- Every time you click the "Move Div" button, we first grab the div’s current left position and convert it from a string (like "100px") to a number.
- We add 100px to that value and update the div’s position on the page.
- We check if the new position equals 400px—if it does, we show the "hey" alert.
内容的提问来源于stack exchange,提问作者aaron lilly
相关产品推荐
相关产品推荐

