gpt4 book ai didi

javascript - CSS 过渡不适用于 offsetLeft 上最右边的 div

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:22 24 4
gpt4 key购买 nike

我有五个 div。您可以单击其中的四个 div,这将运行一个函数,使用 div.offsetLeftdiv.offsetTop 将您单击的 div 移动到第五个 div 的坐标。前三个 div 都可以正常工作,但如果您首先单击最右边的 div,则在移动到坐标时不会应用过渡效果。如果您首先单击任何其他 div,然后单击最右边的 div,将应用转换。

如果你这样做只有两个或三个 div,问题仍然存在。 (您必须从 parties 数组中删除相应的 id,以及 html 元素)。

jsfiddle:https://jsfiddle.net/zjystr2u/

为 html 中的 javascript 道歉。从未使用过 jsfiddle,也不知道如何让它在 html 之后加载 javascript。

最佳答案

当您 getCurrentPosAll()position 从默认的 static 更改为 absolute 时,会发生一些问题/p>

您可以在更改 topleft 之前运行 getCurrentPosAll() 以正确设置它们的默认值。

var selected = document.getElementById("selected");
var selectedX = selected.offsetLeft;
var selectedY = selected.offsetTop;

parties = ['opt1', 'opt2', 'opt3', 'opt4'];
getCurrentPosAll(); // (NEW) Make sure their defaults are set.

function moreTest(e) {
var party = e.target
party.style.left = selectedX + "px";
party.style.top = selectedY + "px";
}

function getCurrentPosAll() {
for (var idx = 0; idx < parties.length; idx++) {
var currentDiv = document.getElementById(parties[idx]);
var x = currentDiv.offsetLeft;
var y = currentDiv.offsetTop;
currentDiv.style.left = x + "px";
currentDiv.style.top = y + "px";
}

for (var idx = 0; idx < parties.length; idx++) {
var currentDiv = document.getElementById(parties[idx]);
currentDiv.style.position = "absolute";
}
}
.wrapper {
display: flex;
justify-content: space-around;
width: 75%;
margin: 0 auto;
}

.selected {
width: 100px;
height: 150px;
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
background-color: black;
opacity: 0.6;
z-index: 1;
}

.opt {
width: 100px;
height: 150px;
cursor: pointer;
transition: top 0.7s, left 0.7s;
}

.opt1 {
background-color: red;
}

.opt2 {
background-color: blue;
}

.opt3 {
background-color: orange;
}

.opt4 {
background-color: green;
}
<div class="wrapper">
<div class="selected" id="selected"></div>
<div class="opt opt1" id="opt1" onclick="moreTest(event)"></div>
<div class="opt opt2" id="opt2" onclick="moreTest(event)"></div>
<div class="opt opt3" id="opt3" onclick="moreTest(event)"></div>
<div class="opt opt4" id="opt4" onclick="moreTest(event)"></div>
</div>

我不确定为什么会这样。我认为这与浏览器如何以及何时 计算过渡的初始值有关。最后一个元素的 CSS 更改被批处理到 1 个更新中。
因此它将立即收到更新后的 topleft 值,而其他元素将收到 2 个更新,其中一个具有默认的 top >left 然后是更新后的值。使他们的过渡正常工作。
很可能是因为最后一个元素的 CSS 发生了变化,它们的 css 更新应用于 2 次更新而不是 1 次。

关于javascript - CSS 过渡不适用于 offsetLeft 上最右边的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45476120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com