所以我的任务之一是创建一个窗口,在其中我应该能够附加不同的应用程序。窗口本身或多或少已经完成,我正在尝试使组件可拖动。
我相信大部分工作都已完成且确实有效。我可以在控制台中看到,当我移动鼠标时,X和Y位置实际上正在改变,但是窗口本身并没有移动。
我相信这是因为pos3和pos4从未获得价值,它们都未定义,我也不知道我做错了什么。我希望你们能理解我的追求,并能为我指明正确的方向。
提琴: https://jsfiddle.net/wLx2qgu0/
这是我的代码,变量命名错误:
const template = document.createElement('template')
template.innerHTML = `
<div id="container">
<h1 id="mover">
<span class="dot" style="background:#ED594A;"></span></h1>
<!-- <chat-board></chat-board> -->
</div>
<!--container end-->
<style>
.dot {
margin-top: 4px;
height: 12px;
width: 12px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
}
#container {
height: 525px;
width: 360px;
margin: 100px auto;
background: #f7f7f7;
box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
border-radius: 20px;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
position: absolute;
z-index: 9;
}
#mover {
background: #1F030C;
color: white;
margin: 0;
padding: 10px 100px;
text-transform: uppercase;
font-size: 18px;
font-weight: normal;
border-top-left-radius: 20px;
border-top-right-radius: 20px;
cursor: move;
z-index: 10;
}
</style>
`
class Window extends window.HTMLElement {
constructor () {
super()
this.attachShadow({ mode: 'open' })
this.shadowRoot.appendChild(template.content.cloneNode(true))
this.pos1 = this.pos1 || 0
this.pos2 = this.pos2 || 0
this.pos3 = this.pos3 || 0
this.pos4 = this.pos4 || 0
this.mover = this.shadowRoot.querySelector('#mover')
this.cont = this.shadowRoot.querySelector('#container')
}
connectedCallback () {
this.dragElement(this.cont)
}
dragElement (event) {
this.mover.addEventListener('mousedown', (e) => {
this.sender(event)
})
}
elementDrag (event) {
event = event || window.event
this.moveWindow(event.clientX, event.clientY)
}
moveWindow (x, y) {
this.pos1 = this.pos3 - x
this.pos2 = this.pos4 - y
this.pos3 = x
this.pos4 = y
this.style.top = this.offsetTop - this.pos2 + 'px'
this.style.left = this.offsetLeft - this.pos1 + 'px'
}
closeDragElement () {
/* stop moving when mouse button is released: */
document.onmouseup = null
document.onmousemove = null
}
// Events
sender (event) {
event = event || window.event
this.pos3 = event.clientX
this.pos4 = event.clientY
console.log(this.pos3)
document.onmouseup = this.closeDragElement
document.onmousemove = this.elementDrag.bind(this)
}
}
window.customElements.define('window-board', Window)
答案 0 :(得分:1)
选中此https://jsfiddle.net/0n4skL3r/
this.dragElement()
函数来附加mousedown
事件。我是在构造函数中完成的。