100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 拖动滑块验证——原生JS

拖动滑块验证——原生JS

时间:2019-10-09 18:08:12

相关推荐

拖动滑块验证——原生JS

**

拖动滑块验证——原生JS

**

大体思路:

1,拖动滑块验证我们首先要分析需要什么事件,怎么触发拖动滑块。

2,首先需要点击事件,当你点击鼠标的时候获取到一个X轴的距离。

3,还需要一个鼠标移动事件,因为当你按下鼠标后并且移上滑块移动的时候,才能实现滑动验证。

4,那么滑动的这个距离怎么求出?当你鼠标点击的时候使用event对象获取X轴的位置赋值给变量down,当鼠标进行移动时,通过event对象获取一个X轴的位置赋值给变量move,这个位置是一直在变的。通过move - down = ?;获取的就是滑块移动的距离。

<!DOCTYPE html><html><head><meta charset="utf-8"><title>拖动滑块验证</title><link rel="stylesheet" type="text/css" href="Demo.css"/></head><body><header><img src="滑块验证.png" alt=""><img id="yanzheng" src="验证.png" alt=""></header><section><article><p class="yanzheng" id="yanzhengafter" style="user-select: none">拖动滑块验证</p><p class="huakuai" id="huakuai"></p></article></section></body></html><script src="Demo.js" type="text/javascript" charset="utf-8"></script>

*{margin: 0px;padding: 0px;list-style: none;text-decoration: none;color:black;}article{width: 320px;margin: 100px auto;position: relative;}.yanzheng{text-align: center;line-height: 40px;width: 100%;height: 40px;background-color: darkgrey;}.huakuai{position: absolute;top: 0px;left: 0px;width: 40px;height: 40px;text-align: center;line-height: 40px;background-color: rebeccapurple;color: white;font-weight: bold;cursor: pointer;z-index: 3;}header{width: 320px;margin: 100px auto;position: relative;}header :nth-child(1){width: 300px;height: 180px;}header :nth-child(2){position: absolute;top: 60px;left: 0px;}

var yanzheng = document.getElementById('yanzheng'),huakuai = document.getElementById('huakuai'),yanzhengAfter = document.getElementById('yanzhengafter');huakuai.onmousedown = function(event){var down = event.clientX;//获取鼠标点击滑块的X轴位置。huakuai.onmousemove = function(event){var move = event.clientX - down;//根据鼠标移动时的位置和鼠标点击滑块的X轴位置,求出滑块需要移动的距离。if(move >= 0 && move <= 280){//设定一个滑块最大最小移动的位置huakuai.style.left = move + 'px';yanzheng.style.left = move + 'px';if(yanzheng.offsetLeft == 155){//滑块验证成功的时候yanzhengAfter.innerHTML = '验证成功';yanzhengAfter.style.backgroundColor = 'yellowgreen';yanzhengAfter.style.color = 'white';}else{yanzhengAfter.innerHTML = '拖动滑块验证';yanzhengAfter.style.backgroundColor = 'darkgrey';yanzhengAfter.style.color = 'black';}}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。