JavaScript implements the basic code of Table column width dragging
Because jquery is very popular in front-end development, the source code is also based on jquery. In fact, it can be said that development is already dependent on it. Who makes it so useful?
In some cases, we need to implement the div or table column used for layout, which can be dragged as needed to change the layout width. Then, we know that we cannot add events to the border of any html container. Therefore, we need to add the left and right borders of a div virtual container of approximately 5-10 PX width. That is to say, we need to add a div for the original container to serve as a certain boundary of the container, so that the virtual boundary can be used to add mouse events. This is the premise.
The following code is the drag event that we need to add to the div of the virtual border (the drag attribute of CSS3 is not compatible currently ).
var isDrag = false;
Var x = 0; // a reference for the operation object on the x axis
$("#resizerCol").mousedown(function () { isDrag = true; }); $("#resizerCol").mouseup(function () { isDrag = false; }); $("#resizerCol").mouseout(function () { isDrag = false; }); $("#resizerCol").mousemove(function (e) { if (isDrag) { if (x != 0) { if (x > e.pageX) { console.log("left"); } else { console.log("right"); } } } });
Yes. The ID resizerCol in the source code is the object we drag. However, it is not so smooth to drag. Please give your comments.
Later, I found that the above Code was too strict, changed one by one, and then found perfection. Paste the new code again, and no longer need to look for the jquery ui and Other plug-ins above to solve such a small problem !!
/* *The event start have to be the virtual partition line. *But the event end just should be that mouse up in the table. * Maybe this just is a virtual "drag" event. */ $("#resizerCol").mousedown(function () { isDrag = true; }); $("#whlayout").mouseup(function () { isDrag = false; });
$ ("# Whlayout"). mousemove (function (e) {if (isDrag) {// TODO directly use e. pageX to adjust the width of the container to adjust the width
} });
The container whose ID is whlayout is actually the parent container of the div whose width is adjusted. Generally, its width occupies 100% of the window during browsing, otherwise it needs to be adjusted by nearly half.