html实现滑动解锁_js滑动解锁(原创)

var box = document.querySelector("#box");

var content = document.querySelector("#content");

var shadow = document.querySelector("#shadow");

var tip = document.querySelector("#tip");

var block = document.querySelector("#block");

var maxWidth = content.clientWidth - shadow.offsetWidth

var maxHeight = content.clientHeight - shadow.offsetHeight;

var ranX = Math.round(Math.random() * maxWidth);

var ranY = Math.round(Math.random() * maxHeight);

shadow.style.left = ranX + "px";

shadow.style.top = ranY + "px";

tip.style.top = ranY + "px";

tip.style.backgroundPosition = -ranX + "px " + (-ranY) + "px";

block.onmousedown = function(e) {

var ev = event || e;

var startX = ev.x;

document.onmousemove = function(e) {

var ev = event || e;

var x = ev.x;

var left = x - startX;

if (left <= 0) {

left = 0;

}

if (left >= maxWidth) {

left = maxWidth;

}

block.style.left = left + "px";

tip.style.left = left + "px";

}

}

document.onmouseup = function() {

document.onmousemove = null;

if (Math.abs(tip.offsetLeft - shadow.offsetLeft) <= 2) {

alert("成功");

} else {

block.style.left = 0;

tip.style.left = 0;

add();

}

}

function add() {

var ranX = Math.round(Math.random() * maxWidth);

var ranY = Math.round(Math.random() * maxHeight);

shadow.style.left = ranX + "px";

shadow.style.top = ranY + "px";

tip.style.top = ranY + "px";

tip.style.backgroundPosition = -ranX + "px " + (-ranY) + "px";

}

window.ondragstart = function() {

return false;

}


版权声明:本文为weixin_34729012原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。