如何使用纯JavaScript代码调整div的垂直或水平大小,而不使用CSS属性,只需从高度或宽度进行调整?
HTML
<div id="container">
<div id="top-panel"> This is the top side's content! </div>
<div id="bottom-panel">
<div id="drag"></div>
bottom content!</div>
JavaScript (JS)
var isResizing = false,
lastDownX = 0;
$(function () {
var container = $('#container'),
top = $('#top-panel'),
bottom = $('#bottom-panel'),
handle = $('#drag');
document.addEventListener("mousedown", function(e){
isResizing = true;
lastDownX = e.clientY;
});
document.addEventListener("mousemove", function(e){
// we don't want to do anything if we aren't resizing.
if (!isResizing)
return;
console.log("e.clientY ", e.clientY, container.offset().top)
var offsetRight = container.height() - (e.clientY - container.offset().top);
top.css('bottom', offsetRight);
bottom.css('height', offsetRight);
}); document.addEventListener("mouseup", function(e){
// stop resizing
isResizing = false;
});
}); 垂直调整 div 的大小
var div1 = document.getElementById("DivOne");
var dRect = div1.getBoundingClientRect();
var scrollBarWidth = 6;
var w = window.innerWidth - 2*dRect.left - scrollBarWidth;
var h = window.innerHeight - 2*dRect.top - scrollBarWidth;
div1.style.width = w.toString() + "px";
div1.style.height = h.toString() + "px";
工作示例:单个DIV大小与文档窗口相同
function handleContainerHeight(e) {
const container = document.querySelector("#elmentToResize");
container.style.height = `${e.clientY}px`;
}
const handleDragMouseDown = (e) => {
document.addEventListener("mousemove", handleContainerHeight);
document.addEventListener("mouseup", handleDragMouseUp, { once: true });
};
const handleDragMouseUp = (e) => {
document.removeEventListener("mousemove", handleContainerHeight);
};
<div className="resize-container">
<div className="resize-wrapper" onMouseDown={handleDragMouseDown}>
<img src="image.png" alt="Drag Icon" />
</div>
</div>
你可以使用 style
来实现它,例如:
getElementById('div_register').style.width='500px';
getElementById('div_register').style.height='500px';
document.onmouseout = function (event) { // document.getElementById("clickable").innerHTML = ""; } } </script> - Ando Khachatryan