调整div的垂直或水平大小

5
如何使用纯JavaScript代码调整div的垂直或水平大小,而不使用CSS属性,只需从高度或宽度进行调整?

展示一些你尝试过的代码,或者你如何尝试实现这个变化。 - Andy Donegan
<div id="clickable" style="background-color: aqua;width:100px;height: 100px;"> </div> <script> var clickable = document.getElementById("clickable"); clickable.onmousemove = function(event){ var x = e.clientX; var y = e.clientY; var coor = "Coordinates: (" + x + "," + y + ")"; document.getElementById("clickable").innerHTML = coor;
document.onmouseout = function (event) { // document.getElementById("clickable").innerHTML = ""; } } </script>
- Ando Khachatryan
4个回答

4

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 的大小


2
我发现以下结果是最好的:
 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大小与文档窗口相同


0
    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>
   

1
你好,欢迎来到stackoverflow。 通过为源代码添加一些文本描述,您可以改进您的答案。 - IARI

0

你可以使用 style 来实现它,例如:

getElementById('div_register').style.width='500px';
getElementById('div_register').style.height='500px';

1
不,你没有理解我的意思。你必须使用垂直或水平调整光标。 - Ando Khachatryan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接