<style>
#box {
width: 200px;
height: 200px;
background-color: red;
position: fixed;
}
</style>
<body>
<script>
// 2、用键盘上下左右移动页面的div
let box = document.createElement('div'); // 给页面创建元素
document.body.appendChild(box); // 把创建的元素添加到body中
box.setAttribute('id', 'box') // 给元素添加id
document.onkeydown = function (e) {
switch (e.keyCode) { // box.style.left = box.style.left =
case 37: // 做判断当元素向移动位置距离文档X坐标为 0时 让元素的左移动坐标为0 使之不能移出文档显示区
box.style.left = box.offsetLeft <= 0 ? 0 + 'px' : `${box.offsetLeft - 5}px`
break;
case 39:
// 做判断当元素向移动位置距离文档X坐标为 最大值(减去元素的宽度)时 让元素的右移动坐标为最大值使之不能移出文档显示区
box.style.left = box.offsetLeft >= window.innerWidth - 200 ? (window.innerWidth - 200) + 'px' : `${box.offsetLeft + 5}px`
break;
case 38:
// 做判断当元素向移动位置距离文档Y坐标为 0时 让元素的上移动坐标为0 使之不能移出文档显示区
box.style.top = box.offsetTop <= 0 ? 0 + 'px' : `${box.offsetTop - 5}px`
break;
case 40:
// 做判断当元素向移动位置距离文档Y坐标为 最大值(减去元素的宽度)时 让元素的下移动坐标为最大值使之不能移出文档显示区
box.style.top = box.offsetTop >= window.innerHeight - 200 ? (window.innerHeight - 200) + 'px' : `${box.offsetTop + 5}px`
break;
}
}
</script>
JS实现用键盘上下左右键移动页面的div进行移动,并且不能移出页面
最新推荐文章于 2023-11-18 23:34:40 发布