Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

javascript - Recommended way to have drawer resizable?

I would like to have the material ui drawer's width resizable through a draggable handle. My current approach is to have a mousevent listener on the whole app which checks if handle was pressed and updates the width according to mouse position on every mouse move.

This however requires a constant mouseevent listener on the whole app which seems to be overkill for a simple resize feature.

Are there better/ recommended ways of doing the resize?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use indicator dragger with mousedown on it.

Here for example

// styles
dragger: {
  width: '5px',
  cursor: 'ew-resize',
  padding: '4px 0 0',
  borderTop: '1px solid #ddd',
  position: 'absolute',
  top: 0,
  left: 0,
  bottom: 0,
  zIndex: '100',
  backgroundColor: '#f4f7f9'
}

...

state = {
  isResizing: false,
  lastDownX: 0,
  newWidth: {}
};

handleMousedown = e => {
  this.setState({ isResizing: true, lastDownX: e.clientX });
};


handleMousemove = e => {
  // we don't want to do anything if we aren't resizing.
  if (!this.state.isResizing) {
    return;
  }

  let offsetRight =
    document.body.offsetWidth - (e.clientX - document.body.offsetLeft);
  let minWidth = 50;
  let maxWidth = 600;
  if (offsetRight > minWidth && offsetRight < maxWidth) {
    this.setState({ newWidth: { width: offsetRight } });
  }
};

handleMouseup = e => {
  this.setState({ isResizing: false });
};

componentDidMount() {
  document.addEventListener('mousemove', e => this.handleMousemove(e));
  document.addEventListener('mouseup', e => this.handleMouseup(e));
}

...

<Drawer
  variant="permanent"
  open
  anchor={'right'}
  classes={{
    paper: classes.drawerPaper
  }}
  PaperProps={{ style: this.state.newWidth }}
>
  <div
    id="dragger"
    onMouseDown={event => {
      this.handleMousedown(event);
    }}
    className={classes.dragger}
  />
  {drawer}
</Drawer>

The idea is, when click the dragger, it will resize width Drawer followed mouse move.

Play DEMO.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...