本来想要趁这几天多做一些Vue的改写,跟原生JS版同步,但时间上蛮赶的,又遇上一些难题。因此这几天先以原生JS版为主。可以预期到了第三十天铁人赛结束,Vue版本应该没办法同步完成。但这个系列的文章会持续到Vue版本开发完才会结束。
预期效果
从unsplash api取得随机图片,渲染到一个方块中,然後再拖曳到另一个空白的方块中来填满。拼图游戏应该会用到类似的效果。
请大家先来看CodePen:
https://codepen.io/zyrxdkoz/pen/MWomYzG
实作逻辑
html部分
<div class="empty">
// 启用draggable属性,是true的话就可以拖曳图片
<div class="fill" draggable="true"></div>
</div>
<div class="empty"></div>
<div class="empty"></div>
<div class="empty"></div>
<div class="empty"></div>
css部分
.empty {
height: 150px;
width: 150px;
margin: 10px;
border: solid 3px black;
background: white;
}
.fill {
// 使用unsplash api
background-image: url('https://source.unsplash.com/random/150x150');
background-size: cover;
height: 145px;
width: 145px;
cursor: pointer;
}
.hold {
border: solid 5px #ccc;
}
.hovered {
background-color: #333;
border-color: white;
border-style: dashed;
}
@media (max-width: 800px) {
body {
flex-direction: column;
}
}
javascript部分
const fill = document.querySelector('.fill')
const empties = document.querySelectorAll('.empty')
// 在有fill选择器的div放上监听器
// ''当中的名称都是DOM API预设好的行为,行为发生後就启动相关连的函式
fill.addEventListener('dragstart', dragStart)
fill.addEventListener('dragend', dragEnd)
// 迭代阵列中每个属性的值
for(const empty of empties) {
empty.addEventListener('dragover', dragOver)
empty.addEventListener('dragenter', dragEnter)
empty.addEventListener('dragleave', dragLeave)
empty.addEventListener('drop', dragDrop)
}
function dragStart() {
// 当div被拖曳的时候,加上hold属性(会出现灰白边框)
this.className += ' hold'
// 同时也要将div改成白色,但为了避免与hold发生同步冲突,因此使用非同步语法setTimeout来加上invisible选择器。
setTimeout(() => this.className = 'invisible', 0)
}
function dragEnd() {
// 停止拖曳行为後,加回fill选择器
this.className = 'fill'
}
function dragOver(e) {
// 停止浏览器预设行为:拒绝透过拖曳来执行submit
e.preventDefault()
}
function dragEnter(e) {
// 停止浏览器预设行为:拒绝透过拖曳来执行submit
e.preventDefault()
// 当拖曳图片滑过任一个<div>时,加上hovered选择器
this.className += ' hovered'
}
function dragLeave() {
// 当拖曳图片滑过并离开任一个<div>时,将该<div>的class指定为empty。
this.className = 'empty'
}
function dragDrop() {
// 清空hovered选择器
this.className = 'empty'
// 拖曳到<div>後放掉,即是dragDrop行为,
// 此时在<div>当中加入child dom,也就是div.full
this.append(fill)
}
参考资料:
HTML Drag and Drop API
>>: Day 10-假物件 (Fake) - 虚设常式 (Stub)-2 (核心技术-2)
昨天介绍了computed的基本使用方式,今天多讲一点点有关methods的, 大家准备好了吗ε٩(...
今天先来谈一下浮点运算的问题,在ARMv8的架构下,主要还是依IEEE 754的规定来作运算标准,唯...
我是仓颉输入法的使用者,在 windows 10 之前,微软仓颉输入法是可以选择只显示 big5 字...
这应该是这次参赛的最後作品了 来挑战用jQuery做一个ToDoList 首先先写简单的架构 一个i...
API Blueprint(蓝图)。一种用於 Web API 的强大的高级 API 描述语言。AP...