简体   繁体   中英

How change a div position onclick

I have a div positioned like this:

#gr{
    position: relative;
    top:135px;
    left:40px;
    display: inline-flex;
    align-items: center;
    width: 70px;
    margin:0px;
}

I also have 3 simple buttons that each one should change the div to a specific position.

I've created a new div for each button and change the display from none to "block". This works but i will need to this for another 9 that i need to create and it will be too repetitive.

How can i do this with js?

You can do it Using CSS custom properties :

HTML

<div class="container">
    <button id="right" class="btn">Right</button>
    <button id="left" class="btn">Left</button>
    <button id="bottom" class="btn">Bottom</button>
    <button id="center" class="btn">Center</button>

    <div class="parent-div">
        <div id="div" class="div"></div>
    </div>
</div>

CSS

::root {
  --left: 0px;
  --top: 0px;
  --translate: 0px;
}

.container {
  width: 100%;
  height: 100vh;
  background-color: lightgoldenrodyellow;
}
.parent-div {
  width: 100%;
  height: 100%;
  position: relative;
}
.div {
  width: 80px;
  height: 80px;
  background-color: lightcoral;
  position: absolute;
  top: var(--top);
  left: var(--left);
  transform: translate(var(--translate), var(--translate));
}

.btn {
  padding: 10px 5px;
}

JS

let divEl = document.getElementById("div");

document.getElementById("right").addEventListener("click", () => {
  divEl.style.setProperty("--left", "500px");
  divEl.style.setProperty("--top", "calc(100vh-80px)");
  divEl.style.setProperty("--translate", "0px");
});

document.getElementById("left").addEventListener("click", () => {
  divEl.style.setProperty("--left", "0px");
  divEl.style.setProperty("--top", "calc(100vh-80px)");
  divEl.style.setProperty("--translate", "0px");
});

document.getElementById("bottom").addEventListener("click", () => {
  divEl.style.setProperty("--top", "100vh");
  divEl.style.setProperty("--translate", "0px");
});

document.getElementById("center").addEventListener("click", () => {
  divEl.style.setProperty("--left", "50%");
  divEl.style.setProperty("--top", "50%");
  divEl.style.setProperty("--translate", "-50%");
});

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