撰写时间:2019.04.24
今天学会了一个新技能,动态获取鼠标位置,可以在网页上随机移动图标,可以应用在一些个性的导航交互或者页面icon交互。
首先要设置一张图片: 在写样式的时候除了基本宽高,导入图片,最重要的还是位置设置position,除了absolute属性,还有fixed和relative属性可以选择,因为可以这些属性通过"left"、“top”、“right” 以及"bottom" 属性来规定它的位置。而position的另一个值static会忽略任何top、bottom、left 或 right 声明,所以不可用。
图片代码片段:
接下来就是写代码了。
首先获取到图片的ID:
var img = document.getElementById('kitty');
设置图片的onmousedown鼠标按下事件,按下之后获取widow触发对象:
img.onmousedown = function (event) {
var e = event || window.event,
t = e.target || e.srcElement,
获取鼠标按下时的坐标x1,y1:
x1 = e.clientX,
y1 = e.clientY,
获取鼠标按下时的左右偏移量:
skewingLeft = this.offsetLeft,
skewingTop = this.offsetTop;
调用鼠标移动事件,获取window触发对象:
document.onmousemove = function (event) {
var e = event || window.event,
t = e.target || e.srcElement,
获取鼠标移动时的动态坐标:
x2 = e.clientX,
y2 = e.clientY,
获取鼠标移动时的坐标的变化量:
x = x2 - x1,
y = y2 - y1;
给图片赋值位置属性值:
img.style.left = (skewingLeft + x) + 'px';
img.style.top = (skewingTop + y) + 'px';
}
调用鼠标松开事件,给鼠标移动事件赋值为null:
document.onmouseup = function () {
this.onmousemove = null;
}
}
})
插件调用:
完。。
猜您喜欢的文章:
[2018UI课程总结(UI理论篇)](https://blog.youkuaiyun.com/weixin_42359237/article/details/86813330)
[什么是Java算数运算符?](https://blog.youkuaiyun.com/weixin_42359237/article/details/89076496)
[令程序员泪流满面的瞬间,实在忍不住笑了](https://blog.youkuaiyun.com/weixin_42359237/article/details/89049246)
[Oracle约束怎么写?](https://blog.youkuaiyun.com/weixin_42359237/article/details/89048534)
[AE基础界面设置和旋转加载案例](https://blog.youkuaiyun.com/weixin_42359237/article/details/88871178)
[《酒店管理系统——桑拿、沐足模块》项目研发阶段性总结](https://blog.youkuaiyun.com/weixin_42359237/article/details/88871226)
[Oracle 基础知识汇总](https://blog.youkuaiyun.com/weixin_42359237/article/details/88872296)
[PS快捷键](https://blog.youkuaiyun.com/weixin_42359237/article/details/87898135)
[如何使用Oracle视图?](https://blog.youkuaiyun.com/weixin_42359237/article/details/89048617)
[AE圆点加载动画制作过程](https://blog.youkuaiyun.com/weixin_42359237/article/details/89219118)
[如何使用Collections解决多线程安全问题](https://blog.youkuaiyun.com/weixin_42359237/article/details/89256449)
[如何使用System获取系统环境变量](https://blog.youkuaiyun.com/weixin_42359237/article/details/89256171)