我的一个div动态输出:
style="position: relative; left: 77px; top: -14px;"
当我使用拖动时。
我怎样才能将其保存在 php 变量中并将其存储在数据库中。
这是一种方法。但请注意,这使用 jQuery、jQuery UI 和 PHP 页面来处理和保存数据。换句话说,这是一个低效的混乱。应该很快就会有人想出更好的方法。
这个答案使用了这个答案中的code
,感谢Simen Echholt:https://stackoverflow.com/a/4139860/3186769
要查看div
是否被拖动,我们首先检查div
上是否有mousedown
事件。如果有,那么我们在有mouseup
之前检查它是否有mousemove
事件。如果有,则div
已被拖动。
如果div
已被拖动,我们将发布left
和top
位置。以下是实现这一点的 JavaScript:
// For the sake of simplicity, let us assume the div had an id "d".
$(function() {
var isDragging = false;
$("#d")
.mousedown(function() {
$(window).mousemove(function() {
isDragging = true;
$(window).unbind("mousemove");
});
})
.mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
$(window).unbind("mousemove");
if (wasDragging) {
var left = $("#d").position().left;
var top = $("#d").position().top;
$.post("backend.php", {left: left, top: top});
}
});
$("#d").draggable(); // allow the div to be dragged.
});
下面是backend.php
的外观示例。这是我们的javascript发布到的PHP页面。
<?php
if (isset($_POST['left']) && isset($_POST['top']))
{
$db = new mysqli("localhost", "test", "test", "test") or die("This error message will not be visible on your HTML page unless you add a function in the jQuery post method to handle the returned output");
$res = $db->query("INSERT INTO rememberPosition (left, top) values (" . $db->escape_string($_POST['left']) . ", " . $db->escape_string($_POST['top']) . ")");
$db->close();
}
?>
div 的 HTML 非常简单,它应该看起来像这样:
<div id="d" style="<?php require('memory.php'); echo $styleString; ?>">Here is a div with super-powers... It can actually fly around :)</div>
我们在其中加载保存的位置值 memory.php
.下面是memory.php
的外观示例:
<?php
$styleString = "position: relative; left: 0px; top: 0px;";
$db = new mysqli("localhost", "test", "test", "test") or die("Error connecting to database.");
if ($res = $db->query("SELECT left, top FROM rememberPosition"))
{
if ($row = $res->fetch_assoc())
{
$styleString = "position: relative; left: " . $row['left'] . "px; top: " . $row['top'] . "px;";
}
}
$db->close()
?>
希望对:)
有所帮助 在使用此方法之前,您应该等待更好的方法。
编辑:
您应该添加 jQuery 和 jQuery UI 才能使此示例正常工作。
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
任何一项都可以工作
$var = "style="position: relative; left: 77px; top: -14px;"";
$var = 'style="position: relative; left: 77px; top: -14px;"';
$var = addslashes('style="position: relative; left: 77px; top: -14px;"');
最后一个真的毫无意义,但我想我会把它放在那里供参考。我建议中间选项是最好的方法。
数据库插入将处理任何必要的转义,假设您使用 ready. 语句。