Ant Design组件库中的Modal组件实现可拖动/拖拽功能封装的组件
实现功能:仅Modal的标题区域可拖拽,即实现了拖拽功能,又不影响弹窗内部交互操作。
js代码:
export default class DraggableModal extends ponent {constructor(props) {this.state = {top: 0,left: 0,csstop: 0,cssleft: 0,x: 0,y: 0,flage: false,position: null,}}mouseDown = (e) => {let target = e.target,_parent = target.offsetParent;this.setState({top: _parent.offsetTop,left: _parent.offsetLeft,csstop: _parent.offsetTop,cssleft: _parent.offsetLeft,x: e.clientX,y: e.clientY,flage: true,position: 'fixed'});window.onmousemove = this.mouseMove;}mouseMove = (e) => {const { flage, top, left, x, y } = this.stateif (flage) {let curX = e.clientX,curY = e.clientY,disX = curX - x,disY = curY - ythis.setState({cssleft: parseInt(left, 0) + disX,csstop: parseInt(top, 0) + disY,});}}mouseUp = (e) => {const dom = e.target.offsetParentthis.setState({flage: false,top: dom.style.top,left: dom.style.left,});window.onmousemove = null}componentWillUnmount() {window.onmousemove = null}render() {const { title, style = {}, wrapClassName, ...otherProps } = this.propsconst { csstop, cssleft, position } = this.stateconst newTitle = (<divclassName="dragtitle"onMouseDown={this.mouseDown}onMouseUp={this.mouseUp}>{title}</div>);const newStyle = { ...style, marginTop: csstop || style.marginTop, marginLeft: cssleft || style.marginLeft, position, top: '0', left: '0' }const wrapclass = `dragmodal ${wrapClassName}`return (<Modal {...otherProps} title={newTitle} style={newStyle} wrapClassName={wrapclass} maskClosable={false} />)}}
样式代码:
.dragmodal{.ant-modal-content{position: static;}.dragtitle{padding: 8px 24px;cursor: move;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;}}