谁能告诉我为什么悬停的动作在附加框中不起作用?

时间:2014-05-27 14:56:16

标签: jquery css hover append

我正在尝试做一些简单的事情,但我遇到了这个问题。

当我通过按钮插入新框时,悬停的动作在附加框中不起作用。

这是一个例子:jsfiddle

$("#insert").click(function() {

  $("body").append('<div class="box"><div class="inside-box"></div></div>');

});

4 个答案:

答案 0 :(得分:2)

您可以通过CSS代替:

<强> JSFiddle

#insert{
   float:left;
   width:99%;
   padding:7px;
   background:#093;
   text-align:center;
   margin-bottom:10px;
   cursor:pointer;
}

.box{
    position:relative;
    width:250px;
    height:150px;
    background:#09F;
    float:left;
    margin-right:10px;
    margin-bottom:10px;
}

/*Added this code*/
.box:hover .inside-box{
    height:70px;
}

.inside-box{
   transition:.3s;              /*Added this line*/
   -webkit-transition:.3s;      /*Added this line*/
   -moz-transition:.3s;         /*Added this line*/
   position:absolute;
   width:100%;
   height:10px;
   background:#000;
   bottom:0;
}

这样做的好处是可以编写更少的代码,更易于理解和更好的性能。

缺点是它只适用于IE10 and above。所有其他浏览器工作正常(铬,歌剧,野生动物园等)。

答案 1 :(得分:1)

用一句话:Delegation

现在,在阅读上述链接后,您将看到要使用事件委派,您需要将.on与选择器参数一起使用。

hover本身不是事件,它是.mouseenter/.mouseleave的快捷方式。通过组合这两个事件,您可以重新创建委派的hover

$(document).on({
    mouseenter : function () {
        //over

        $(this).find(".inside-box").animate({height: '70px'},"fast" ); 
    },
    mouseleave: function () {
        //out

        $(this).find(".inside-box").animate({height: '10px'},"fast" ); 
    }
}, '.box');

小提琴:http://jsfiddle.net/2UDwc/5/

答案 2 :(得分:0)

设置悬停的代码仅针对当时存在的框运行,如果稍后添加更多框,则他们不会神奇地设置事件处理程序 - 您需要自己执行此操作。

尝试将&#39; hover&#39;将代码编入函数(例如setupHover)并在创建它时将其应用于每个新框。

答案 3 :(得分:0)

当悬停代码过滤页面上的元素时,不存在动态元素。您需要使用事件委派。

不幸的是,hover不是可用于事件委派的事件(因为它需要两个回调函数),因此请将onmouseentermouseleave事件一起使用:< / p>

JSFiddle:http://jsfiddle.net/TrueBlueAussie/2UDwc/4/

$("#insert").click(function () {
    $("body").append('<div class="box"><div class="inside-box"></div></div>');
});

$(document).on('mouseenter', ".box", function () {
    //over
    $(this).find(".inside-box").animate({
        height: '70px'
    }, "fast");
}).on('mouseleave', '.box', function () {
    //out
    $(this).find(".inside-box").animate({
        height: '10px'
    }, "fast");
});