其實很簡單點擊記錄狀態,放手狀態重置,先上代碼在說下遇到的問題javascript
<div id='div1' class='move left'></div>
<div id='div2' class='move right'></div>
複製代碼
body{
width: 100%;
}
.move {
width: 100px;
height: 100px;
border: 1px solid red;
box-sizing: boder-box;
position: absolute
}
.left: {
left: 0
}
.right: {
right: 0
}
複製代碼
class Movediv{
constructor(el) {
this.div = document.querySelector(el);
this.init()
}
init() {
this.div.onmousedown = function(e){
this.x = e.clientX - this.div.offsetLeft
this.y = e.clientY - this.div.offsetTop
document.onmousemove = this.fnmove.bind(this)
document.onmouseup = this.fnup.bind(this)
}.bind(this)
}
fnmove(e) {
this.div.style.left = (e.clientX - this.x) + 'px'
this.div.style.top = (e.clientY - this.y) + 'px'
}
fnup(e) {
document.onmousemove = null
document.onmouseup = null
}
}
複製代碼
上面的js就是類實現能夠拖拽的DIV,提一個新需求,拖拽的div左右不能超過左右範圍css
這就用到類繼承的概念了html
class Movediv1 extends Movediv {
<!--這個樣子基本就是繼承movediv裏面全部的方法-->
<!--可是咱們同時須要改寫fnmove方法--> fnmove(e) { <!--保留父的--> super.fnmove(e) this.maxWidth = document.body.clientWidth; if(parsenInt(this.div.style.left) <= 0) { this.div.style.left = 0 } else if(parseInt(this.div.style.left) >= (parseInt(this.maxWidth - 100))){ this.div.style.left = (this.maxWidth - 100) + 'px' } } } 複製代碼
提幾個比較容易犯錯誤的地方前端
看到的某年騰訊的前端面試題,順便實現了下,內容雖小裏面用的東西仍是蠻多的,關於類,繼承等方法,好好學習java