<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.11.0/jquery.js"></script>
</head>
<style>
.drag {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
}
img {
position: absolute;
}
</style>
<body>
<script>
/***
* jq 内置方法的拓展
* jq.extend() 工具的拓展 调用 .extend({}) 相当于添加了一个静态方法 通过
("选择器").xxx() 来调用
* 而这个相当于 *.prototype 相当于添加了一个原型方法 所以可以通过实例调用
*/
</script>
<div class="drag">
被拖拽的元素
</div>
<img src="../五星评价/img/a.jpg" alt="图片" />
<script>
$.extend({}); // 工具方法的拓展
// jq 方法的拓展
$.fn.extend({
drag: function () {
// 此处的this 表示页面所有被选中的元素 是一个 JQuery 对象
// console.log(this);
$(this).mousedown(function (e) {
e = e || window.event;
e.preventDefault();
var _this = this;
// 记录相对的位置= 鼠标距离页面左边的距离 -当前按下的屋里距离左边的距离
var offsetX = e.clientX - $(this).offset().left;
var offsetY = e.clientY - $(this).offset().top;
console.log(offsetX, offsetY);
$(document).mousemove(function (e) {
e = e || window.event;
$(_this).css({
left: e.clientX - offsetX,
top: e.clientY - offsetY,
backgroundColor: 'red',
});
});
// 鼠标抬起的时候 取消掉 输掉移动事件
$(document).mouseup(function () {
$(document).off('mousemove');
});
});
// 保证可以进行链式调用
return this;
},
});
$(function () {
$('div').drag().css({
color: 'blue',
});
$('img').drag().css({
width: '200px',
});
});
</script>
</body>
</html>
网友评论