
JS案例·图片拖动验证
CSS Sprite,我们一般叫他雪碧图或精灵图,它是一种图像拼合技术。该方法是将小图标和背景图像合并到一张图片上,然后利用 css 的背景定位来显示需要显示的图片部分。
精灵图的使用有以下几个优点:
- 减少图片的字节。
- 减少网页的http请求,从而大大的提高页面的性能。
- 解决了网页设计师在图片命名上的困扰,只需对一张集合的图片上命名就可以了,不需要对每一个小元素进行命名,从而提高了网页的制作效率。
- 更换风格方便,只需要在一张或少张图片上修改图片的颜色或样式,整个网页的风格就可以改变。维护起来更加方便。
第一个值是调左右的,当你需要将背景图向右调的时候用正值,向左则为负值 同理将背景图上下调动的时候上是用负值,下是正值

我们通过设置 background-position 属性,来调整背景图的位置

再例如:

如果想要下面的图形,就可以调整第二个参数,例如:

先完成HTML结构

以及CSS样式代码
- /* 整体容器的样式 */
-
- .container {
- width: 280px;
- height: 400px;
- margin: 100px auto;
- }
-
- /* 上方的图片不好看切换一张的样式 */
-
- .container .changeImg {
- text-align: center;
- position: relative;
- font-size: 16px;
- color: rgb(126, 57, 218);
- font-weight: bolder;
- cursor: pointer;
- user-select: none;
- }
-
- /* 前面的图标 */
-
- .changeImg::before {
- content: '';
- display: block;
- position: absolute;
- left: 10%;
- top: calc(50% - 13px);
- width: 26px;
- height: 26px;
- background: url('../img/sx.png') no-repeat;
- background-size: cover;
- background-position: center;
- }
-
- /* img 容器整体样式,包含标题 + 图片 + 滑条 */
-
- .imgContainer {
- height: 320px;
- box-sizing: border-box;
- padding: 15px;
- border: 1px solid #adadad;
- box-shadow: 0px 0px 2px #adadad;
- /* 设置盒子阴影 */
- border-radius: 15px;
- /* 设置圆角 */
- }
-
- /* 上方标题 */
-
- .imgContainer h3 {
- text-align: center;
- margin: 0;
- margin-bottom: 10px;
- }
-
- /* 中间的图片 */
-
- .imgContainer .imgBox {
- width: 100%;
- height: 200px;
- background-repeat: no-repeat;
- position: relative;
- }
-
- /* 可以拖动的图片 */
-
- .imgBox .imgBlock {
- width: 50px;
- height: 50px;
- position: absolute;
- z-index: 10;
- opacity: 0;
- }
-
- /* 图片缺口 */
-
- .imgBox .imgGap {
- width: 50px;
- height: 50px;
- position: absolute;
- background-color: white;
- box-shadow: 0px 0px 3px #adadad;
- /* 设置盒子阴影 */
- }
-
- /* 滑动条 */
-
- .slider {
- width: 100%;
- height: 30px;
- margin: auto;
- margin-top: 15px;
- background-color: #ddd;
- border-radius: 10px;
- position: relative;
- text-align: center;
- line-height: 30px;
- font-size: 14px;
- font-weight: 200;
- }
-
- /* 滑动条的按钮 */
-
- .slider button {
- position: absolute;
- top: -5px;
- left: -2px;
- background: white url('../img/yz.png') no-repeat;
- background-size: 100%;
- border-radius: 50%;
- border: 0;
- width: 40px;
- height: 40px;
- cursor: pointer;
- z-index: 20;
- }
-
- /* 滑动条文字的样式 */
-
- .slider span {
- transition: all .5s;
- }
在完成HTML和CSS后得到如图效果:

图片验证核心其实就是按钮的拖动,也就是位置的计算:

先拿到需要的DOM节点,方便后续操作
接下来就是随机生成验证图片,我这里图片就是放在本地
图片容器以及拖动的图片块设置对应的背景图
空缺图块可以设置的最大 top 值 = 盒子容器的高度 - 空缺图块的高度
let heightRange = imgBox.offsetHeight - imgBlock.offsetHeight;
空缺图块可以设置的最大 left 值 = 盒子容器的宽度的一半 - 空缺图块的宽度
let widthRange = imgBox.offsetWidth / 2 - imgBlock.offsetWidth;
接下来就是随机生成 left 和 top 值
生成图片缺口及拖动图片的位置

为整个滑动条添加鼠标移动效果

设置鼠标抬起事件

完整源码及图片素材免费下载地址:点击免费下载
本专栏将持续更新原生JS案例,提供一些工作中也能用上的一些小案例,详细讲解分析,提神JS开发水平与开发思路的积累,如果文中出现有瑕疵的地方各位通过评论或者私信联系我,我们一起进步,有兴趣的伙伴可以订阅一下:点击关注JS经典案例专栏
