简体   繁体   中英

Increase two divs height on mouse move

I horizontally split a page of the browser with two divs, and I want to increase the height of a div and reduce it in the other using the mouse position on the y axis. It would enlarge the first div when I'm in the upper part of the page and enlarge the second one when I'm at the bottom, but keeping both divs sum height equal to the height of the page.

This is my code

<html><head>
<meta charset="UTF-8">
<style>
*{
    margin: 0 auto;
}
#container{
    height: 100vh
}
#alto{
    width: 100vw;
    height: 50vh;
    background-color: mediumpurple;
}
#basso{
    width: 100vw;
    height: 50vh;
    background-color: royalblue;
}
</style>
</head>
<body>
<div id="alto" onMousemove="myFunction()" ></div>
<div id="basso" ></div>
<script>
function myFunction() {
    var y = event.clientY + "px";
    document.getElementById("basso").style.height =  y ;
    }
</script>
</body>
</html>

Take a look at this.

 var section1 = document.getElementById("section1"); var section2 = document.getElementById("section2"); document.onmousemove = function(event) { section1.style.height = event.clientY + 'px'; section2.style.height = "calc(100% - "+ event.clientY + 'px'; } 
 *{ margin: 0; padding: 0; box-sizing: border-box; } .container{ background: gray; height: 100vh; } #section1, #section2{ height: 50%; transition: all 0.1s; } #section1{ background: hotpink; } #section2{ background: pink; } 
 <div class="container"> <div id="section1"></div> <div id="section2"></div> </div> 

You can achieve a simpler version of this effect (ie. without constantly changing heights relative to the mouse position) with CSS alone.

Working Example:

 body { margin: 0; padding: 0; } div { width: 100vw; height: 50vh; margin: 0 auto; transition: height 0.3s linear; } div:hover { height: 80vh; } body:not(:hover) div { height: 50vh; } div:not(:hover) { height: 20vh; } .alto { background-color: mediumpurple; } .basso { background-color: royalblue; } 
 <div class="alto"></div> <div class="basso" ></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM