【问题标题】:jQuery .append() is not synchronized?jQuery .append() 不同步?
【发布时间】:2015-08-22 06:24:53
【问题描述】:

我的目标是在 div 上添加一个悬停类,并对其产生过渡效果。但我需要先将元素附加到父元素,以使其始终位于其他元素之上。这是在 z-index 不可用时模拟 z-index 效果的技巧(例如 SVG 没有 z-index)。

但在示例 1 中,过渡效果不起作用。我的假设是 addClass() 发生在元素完成附加之前。所以流程是这样的,

调用 append() => 将类添加到元素 => 过渡开始 => 追加 元素,并且当前过渡被取消 => append() 完成 => 没有其他过渡发生

为了证明我的假设,在示例 2 中,我使用 setTimeout() 调用来包裹 addClass()。在这种情况下,过渡工作正常。

那么我的假设是正确的吗?示例 2 中的解决方案是解决这个问题的好方法吗?请帮忙,谢谢!

$('.inner').hover(function(){
    var item = $(this)
    item.parent().append(this);
    if ($('#sel').val() == "1") {
        item.addClass("hover");
    } else {
        setTimeout(function(){
            item.addClass("hover");
        }, 0)
    }    
}, function(){
    $(this).removeClass("hover");
});
.inner {
    position: absolute;
    width: 50px;
    height: 50px;
    background: #999;
    transform: scale(1.0);
    transition: all 0.3s ease-in;
}
.inner.hover {
    transform: scale(1.1)
}
.outer {
    height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="outer">
    <div class="inner" style="left: 0px;">1</div>
    <div class="inner" style="left: 100px;">2</div>
    <div class="inner" style="left: 200px;">3</div>
</div>
<select id="sel">
    <option value="1">1</option>
    <option value="2">2</option>
</select>

【问题讨论】:

  • 我认为这与 .append() 的完成无关,更多的是关于浏览器尚未渲染元素。但这与您所说的相差不远。
  • 为什么不使用jquery添加悬停类而不使用纯css进行过渡?即:内部:悬停{}

标签: javascript jquery html css


【解决方案1】:

是的,你的假设是正确的。引擎removes the element from the DOM and adds it back$.append 使用appendChild)。这就是setTimeout 正常工作的原因。

【讨论】:

  • 谢谢,我想我应该使用 appendChild。
【解决方案2】:

下面的效果一样,不用jQuery。除非有特殊原因使用 jquery 来添加悬停效果。

.inner {
    position: absolute;
    width: 50px;
    height: 50px;
    background: #999;
    transform: scale(1.0);
    transition: all 0.3s ease-in;
}
.inner:hover {
    transform: scale(1.1)
}
.outer {
    height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="outer">
    <div class="inner" style="left: 0px;">1</div>
    <div class="inner" style="left: 100px;">2</div>
    <div class="inner" style="left: 200px;">3</div>
</div>
<select id="sel">
    <option value="1">1</option>
    <option value="2">2</option>
</select>

【讨论】:

  • 是的,这是有特殊原因的。因为我需要对 SVG 元素进行附加技巧。通过这样做,在 Firefox 中,悬停状态将丢失。所以我需要手动将悬停类添加到元素中。
猜你喜欢
  • 2011-07-02
  • 2015-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2022-01-21
相关资源
最近更新 更多