思路很简单, 就是根据鼠标水平移动的了多少, 给对应的 div 加上多少宽度就好.
初次尝试版
demo
封装成组件大概就是下面的.
- import React, { useState } from "react";
- import PropTypes from 'prop-types';
- export default function stretchableDiv(props) {
- const [place, setPlace] = useState();
- const [width, setwidth] = useState();
- return (
- <div id="stretchableDiv" style={props.style}
- onMouseDown={e => {
- let nowbox = document.getElementById("stretchableDiv");
- if (e.clientX> nowbox.clientWidth - 10) {
- nowbox.style.cursor = "col-resize";
- // 记录下鼠标被按下时, 鼠标的位置, 和此时 div 的宽度
- setPlace(e.clientX);
- setwidth(nowbox.clientWidth);
- }
- }}
- onMouseMove={e => {
- let nowbox = document.getElementById("stretchableDiv");
- if (nowbox.style.cursor === "col-resize") {
- nowbox.style.width = `${e.clientX - place + width}px`;
- }
- }}
- onMouseUp={e => {
- // 当鼠标按键被松开时
- document.getElementById("stretchableDiv").style.cursor = "auto";
- }}
- onMouseLeave={e => {
- // 当鼠标离开拉伸区域时
- document.getElementById("stretchableDiv").style.cursor = "auto";
- }}>
- {props.children}
- </div>
- );
- }
- stretchableDiv.propTypes = {
- //div 样式
- style: PropTypes.object
- };
但上面的代码出来的效果是有个小问题的. 当鼠标移动的速度太快时, 鼠标移动到 div 框外, 不完美的点会体现出来, 此时 div 的宽度增加没有跟上鼠标的移动速度.
修改版
demo2
改为监听根节点, 获取的鼠标的对应位置, 然后把宽度加上去.
- import React, { useState , useEffect } from "react";
- import PropTypes from 'prop-types';
- export default function stretchableDiv(props) {
- const [place, setPlace] = useState();
- const [width, setwidth] = useState();
- useEffect(() => {
- function getClientX(e) {
- let nowbox = document.getElementById("stretchableDiv");
- if (nowbox.style.cursor === "col-resize") {
- nowbox.style.width = `${e.clientX - place + width}px`;
- }
- }
- document.getElementById("root").addEventListener("mousemove", getClientX);
- return function clean() {
- document.removeEventListener("mousemove", getClientX);
- };
- });
- return (
- <div id="stretchableDiv" style={props.style}
- onMouseDown={e => {
- let nowbox = document.getElementById("stretchableDiv");
- if (e.clientX> nowbox.clientWidth - 10) {
- nowbox.style.cursor = "col-resize";
- // 记录下鼠标被按下时, 鼠标的位置, 和此时 div 的宽度
- setPlace(e.clientX);
- setwidth(nowbox.clientWidth);
- }
- }}
- onMouseUp={e => {
- // 当鼠标按键被松开时
- document.getElementById("stretchableDiv").style.cursor = "auto";
- }}>
- {props.children}
- </div>
- );
- }
- stretchableDiv.propTypes = {
- //div 样式
- style: PropTypes.object
- };
来源: http://www.jianshu.com/p/dc849b0af658