javascript - 这种效果该如何实现?
本文介绍了javascript - 这种效果该如何实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
当按住鼠标左键不松开时,鼠标在浏览器窗口里移动,能够根据移动的位置画出走过的痕迹,鼠标左键松开时,画图功能不在执行,如果用点击事件很容易就能获取到每次点击的坐标,现在问题是该用什么方法,才能获取到鼠标经过的每一个坐标
解决方案
要完成这个效果,组合使用三个事件就可以了 mousedown
mousemove
mouseup
在鼠标移动的时候时刻获取鼠标的坐标
html
<div class="drag-wrap" id="drag-wrap"></div>
css
body{
background-color: #000;
}
.drag-wrap{
width: 600px;
height: 500px;
margin: auto;
background-color: #fff;
position: relative;
overflow: hidden;
}
.green-dot{
width: 2px;
height: 2px;
border-radius: 100%;
background-color: green;
position: absolute;
}
js
var app = {
init: function () {
var oDragWrap = document.getElementById('drag-wrap');
this.drag(oDragWrap);
},
cDiv: function (tagName, iClass) {
var tag = document.createElement(tagName);
tag.className = iClass ? iClass : '';
return tag;
},
css: function (ele, styleObj) {
for(var attr in styleObj){
ele['style'][attr] = styleObj[attr];
}
},
drag: function (obj) {
var _this = this;
var oDragWrap = document.getElementById('drag-wrap');
var disX,disY,div;
obj.onmousedown = function (ev) {
var ev = ev || event;
disX = this.offsetLeft;
disY = this.offsetTop;
document.onmousemove = function (ev) {
var ev = ev || event;
div = _this.cDiv('div', 'green-dot');
_this.css(div, {
left: ev.clientX - disX + 'px',
top: ev.clientY - disY + 'px'
});
oDragWrap.appendChild(div);
}
document.onmouseup = function () {
this.onmousemove = this.onmouseup = null;
}
return false;
}
}
}
app.init();
这篇关于javascript - 这种效果该如何实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文