Ant Design -- 图片可拖拽效果,图片跟随鼠标移动

Ant Design 图片可拖拽效果,图片跟随鼠标移动,需计算鼠标在图片中与图片左上角的X轴的距离和鼠标在图片中与图片左上角的Y轴的距离。

constructor(props) {
        super(props);
        this.dragDrop = false; // 图片是否被拖动中
        this.apartX = 0; // 鼠标在图片中与图片左上角的X轴的距离
        this.apartY = 0; //鼠标在图片中与图片左上角的Y轴的距离
        this.state = {
            previewVisible: false,
            previewImage: ''
        }
}
    //图片点击查看
    handlePreview = (url) => {
        this.setState({
            previewImage: url,
            previewVisible: true,
        });
    };
    // 关闭图片预览
    closeImgIcon = () => {
        this.setState({
            previewVisible: false
        });
    }
    // 图片跟随鼠标移动
_qxmouseMove = (event) => {
this.dragDrop = false;
} _mouseDown = (event) => { this.dragDrop = true; const imgWrap = this.refs.showPreviewImageWrap; this.apartX = event.pageX - imgWrap.offsetLeft;// 鼠标在图片中与图片左上角的X轴的距离 this.apartY = event.pageY - imgWrap.offsetTop; event.preventDefault(); event.stopPropagation(); } _mouseUp = (event) => { this.dragDrop = false; event.preventDefault(); event.stopPropagation(); } _mouseMove = (event) => { if (!this.dragDrop) { return; }

const imgWrap = this.refs.showPreviewImageWrap; imgWrap.style.left = (event.pageX - this.apartX)+ 'px'; imgWrap.style.top = (event.pageY - this.apartY) + 'px'; event.preventDefault(); event.stopPropagation(); } //图片后缀判断 imgSuffix = (url) => { let suffix = url.substring(url.length - 3); return suffix };
{this.state.previewVisible &&
    <div className="ant-modal-wrap" onMouseMove={this._qxmouseMove.bind(this)}>
       <div className='show_picture_image_wrap'
       onMouseUp={this._mouseUp.bind(this)} 
       onMouseDown={this._mouseDown.bind(this)} 
       onMouseMove={this._mouseMove.bind(this)}
       ref="showPreviewImageWrap" >
          <Icon className="close-imgIcon" type="close-circle" onClick={() => this.closeImgIcon()}/>
          {
            (previewImage.indexOf('.pdf') > 0) ?
               <iframe src={previewImage} frameBorder="0"
               style={{width: '100%', height: '800px'}}></iframe> :
               <img alt="example"  style={{width: '100%'}} src={previewImage}/>
           }
       </div>
    </div>
 }

 在div叫 ant-modal-wrap 增加onMouseMove 设置this.dragDrop=false;即鼠标离开需要拖拽的盒子,则取消拖拽事件。

用onMouseMove做拖拽时要注意iframe,在鼠标经过iframe时,鼠标就会失去控制。

解决:iframe { pointer-events:none; }  (但是iframe的点击,滚动等事件会消失)
posted @ 2019-12-18 11:38  童话里都是骗人的  阅读(2398)  评论(0编辑  收藏  举报