JavaScript实现登录滑块验证

HTML代码如下:



CSS代码如下:

#slide-verify {
    position: relative;
    width: 300px;
    height: 150px;
    margin-left: 100px;
    background-color: #666;
}
#slide-verify>span {
    position: absolute;
    top: 30%;
    width: 16%;
    height: 33%;
    background-color: #fff;
}
#slide-verify>span:nth-child(1) {
    cursor: move;
    z-index: 1;
    background-color: #000;
}

JavaScript代码如下:

window.onload = function () {
    let 
    elementSlideVerify = document.querySelector("#slide-verify") || null,
    elementFirstSlider = document.querySelector("#slide-verify>span:nth-child(1)") || null,
    elementSecondSlider = document.querySelector("#slide-verify>span:nth-child(2)") || null,
    statusFirstSliderClick = 0,
    firstSliderPreLeft
    const 
    FIRST_SLIDER_INIT_LEFT = 20,
    SECOND_SLIDER_LEFT_MIN = FIRST_SLIDER_INIT_LEFT + elementFirstSlider.clientWidth,
    SECOND_SLIDER_LEFT_MAX = elementSlideVerify.clientWidth - elementSecondSlider.clientWidth,
    SECOND_SLIDER_INIT_LEFT = Math.ceil(Math.random() * (SECOND_SLIDER_LEFT_MAX - SECOND_SLIDER_LEFT_MIN)) + SECOND_SLIDER_LEFT_MIN
    ERROR_RANGE = 5

    !elementFirstSlider || (elementFirstSlider.style.left = FIRST_SLIDER_INIT_LEFT + "px")
    !elementSecondSlider || (elementSecondSlider.style.left = SECOND_SLIDER_INIT_LEFT + "px")
    elementFirstSlider.onmousedown = () => statusFirstSliderClick = 1
    elementFirstSlider.onmousemove = e => {
        if (!statusFirstSliderClick)
        return
        e = e || window.e
        firstSliderPreLeft = e.pageX - elementSlideVerify.offsetLeft - FIRST_SLIDER_INIT_LEFT
        if (firstSliderPreLeft >= 0 && firstSliderPreLeft <= SECOND_SLIDER_LEFT_MAX)
            elementFirstSlider.style.left = firstSliderPreLeft
    }
    elementFirstSlider.onmouseup = () => {
        let 
        firstSliderLeftNumber = +elementFirstSlider.style.left.slice(0, elementFirstSlider.style.left.length-2),
        secondSliderLeftNumber = +elementSecondSlider.style.left.slice(0, elementSecondSlider.style.left.length-2)
        statusFirstSliderClick = 0
        if (Math.abs(firstSliderLeftNumber - secondSliderLeftNumber) <= ERROR_RANGE)
            console.log("success")
        else {
            elementFirstSlider.style.left = FIRST_SLIDER_INIT_LEFT
            console.log("error")
        }
    }
}

运行结果如下:

JavaScript实现登录滑块验证_第1张图片

你可能感兴趣的:(javascript,css,前端,html)