jQuery 拖拽拼图验证是一种基于 jQuery 的前端交互验证方式,用户需要通过拖拽将一个碎片拼接到正确的位置来完成验证。这种方式可以有效防止自动化脚本的攻击,提高网站的安全性。
以下是一个简单的 jQuery 拖拽拼图验证的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery 拖拽拼图验证</title>
<style>
#puzzle {
position: relative;
width: 300px;
height: 200px;
border: 1px solid #ccc;
}
.puzzle-piece {
position: absolute;
width: 100px;
height: 100px;
background-color: #eee;
border: 1px solid #ccc;
cursor: move;
}
#target {
position: absolute;
width: 100px;
height: 100px;
background-color: #fff;
border: 2px dashed red;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="puzzle">
<div class="puzzle-piece" style="left: 0px; top: 0px;"></div>
<div class="puzzle-piece" style="left: 100px; top: 0px;"></div>
<div class="puzzle-piece" style="left: 200px; top: 0px;"></div>
<div class="puzzle-piece" style="left: 0px; top: 100px;"></div>
<div class="puzzle-piece" style="left: 100px; top: 100px;"></div>
<div class="puzzle-piece" style="left: 200px; top: 100px;"></div>
<div id="target" style="left: 100px; top: 100px;"></div>
</div>
<script>
$(document).ready(function() {
var target = $('#target');
var pieces = $('.puzzle-piece');
pieces.draggable({
revert: 'invalid',
containment: '#puzzle'
});
pieces.on('dragstop', function(event, ui) {
var piece = $(this);
var offset = piece.offset();
var targetOffset = target.offset();
if (offset.left === targetOffset.left && offset.top === targetOffset.top) {
piece.css('background-color', '#fff');
target.css('border-style', 'solid');
// 验证成功
alert('验证成功!');
} else {
piece.draggable('option', 'revert', true);
}
});
});
</script>
</body>
</html>
containment
属性设置不正确。containment
属性设置为包含拼图容器,如 #puzzle
。通过以上方法,可以有效解决 jQuery 拖拽拼图验证中可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云