一、面向对象
两种编程模式:
面向过程:注重过程
面向对象:注重结果
Js基于对象
对象的特征:
封装 继承 多态
对象的组成:
属性:静态的,对象的描述 --------------------- 变量
方法:动态,对象的行为 -------------------------- 函数
2.call与apply与bind
call apply bind:改变this的指向
普通函数的this------指向window
事件处理函数的this------指向触发事件的对象
构造函数中的this------ S对象
js面向对象封装拖拽效果
在这里插入<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
width: 300px;
height: 300px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<div id="div"></div>
<script>
function Drag(id) {
var _this = this;
this.x=0;
this.y=0;
this.oDiv = document.getElementById(id);
this.oDiv.onmousedown = function (ev) {
_this.down(ev);
return false
}
}
Drag.prototype={
down: function (ev) {
var _this=this;
var ev = window.event || ev;
this.x = ev.clientX - this.oDiv.offsetLeft;
this.y = ev.clientY - this.oDiv.offsetTop;
document.onmousemove = function(ev){
_this.move(ev);
};
document.onmouseup = function (){
_this.up()
}
},
move:function (ev) {
var ev = window.event || ev;
var l = ev.clientX - this.x;
var t = ev.clientY - this.y;
//2.元素随鼠标动
this.oDiv.style.left = l + "px";
this.oDiv.style.top = t + "px";
},
up: function () {
document.onmousemove=document.onmouseup = null;
}
}
new Drag('div')