JavaScript

超轻量级php框架startmvc

JS实现鼠标拖拽盒子移动及右键点击盒子消失效果示例

更新时间:2020-08-13 14:18:01 作者:startmvc
本文实例讲述了JS实现鼠标拖拽盒子移动及右键点击盒子消失效果。分享给大家供大家参考

本文实例讲述了JS实现鼠标拖拽盒子移动及右键点击盒子消失效果。分享给大家供大家参考,具体如下:

1. 鼠标拖拽盒子移动效果


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <style>
 *{
 margin:0;
 padding:0;
 }
 div{
 width: 100px;
 height: 100px;
 background: blue;
 position: absolute;
 }
 </style>
</head>
<body>
<div>
</div>
<script>
 window.onload=function () {
 var oDiv=document.getElementsByTagName("div")[0];
 oDiv.onmousedown=function () {
 document.onmousemove=function (ev) {
 var event=window.event||ev;
 oDiv.style.left=event.clientX+"px";
 oDiv.style.top=event.clientY+"px";
 }
 document.onmouseup=function (){
 document.onmousemove=null;
 document.onmouseup=null;
 }
 }
 }
</script>
</body>
</html>

2. 鼠标右键使盒子消失


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <style>
 *{
 margin: 0;
 padding: 0;
 }
 div{
 width: 100px;
 height: 100px;
 background: red;
 display: block;
 }
 </style>
</head>
<body>
<div>
</div>
<script>
 window.onload=function () {
 document.oncontextmenu=function () {
 var oDiv=document.getElementsByTagName("div")[0];
 oDiv.style.display="none"
 return false
 }
 }
</script>
</body>
</html>

感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试一下运行效果。

JS 鼠标拖拽 盒子移动 右键点击 盒子消失