jQuery在hover上添加一个Class - object literal

时间:2017-12-16 00:24:48

标签: javascript jquery

我试图在鼠标悬停在元素上时将类添加到img,并在鼠标不再位于元素上时删除该类。我使用对象文字表示法。我无法看到选择正确的图像,任何人都可以看到我出错的地方吗?



let Cc = {
    bindEvent: function() {
        $('.title.em-below').hover( function() {
            let selectedtitle = $(this);
            Cc.scaleThumbnail(selectedtitle);
        })
    },
    scaleThumbnail: function(selectedtitle) {
        let $thumbnail = selectedtitle.siblings('.image-thumbnail')
        let img = $thumbnail.children('img');
        console.log(img);
        img.addClass('thumbnail-active');
        img.removeClass('thumbnail-active');
    },
}

.thumbnail-active {
    transform: scale(1.1);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="title em-below">
        Title
    </div>
    <a class="image-thumbnail">
        <div class="wide-thumbnail em-below">
            <img src="https://via.placeholder.com/350x150"/>
        </div>
    </a>                  
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您需要调用CC.bindEvent()来绑定事件处理程序。你的悬停功能需要切换类,而不是添加它,然后立即删除它。

img元素不是$thumbnail的子元素,它是孙子。使用.find()代替.children()

&#13;
&#13;
let Cc = {
    bindEvent: function() {
        $('.title.em-below').hover( function() {
            let selectedtitle = $(this);
            Cc.scaleThumbnail(selectedtitle);
        })
    },
    scaleThumbnail: function(selectedtitle) {
        let $thumbnail = selectedtitle.siblings('.image-thumbnail')
        let img = $thumbnail.find('img');
        //console.log(img.attr('src'));
        img.toggleClass('thumbnail-active');
    },
}


Cc.bindEvent();
&#13;
.thumbnail-active {
    transform: scale(1.1);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="title em-below">
        Title
    </div>
    <a class="image-thumbnail">
        <div class="wide-thumbnail em-below">
            <img src="https://via.placeholder.com/350x150"/>
        </div>
    </a>                  
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

问题在于此行,因为未捕获img标记。

$thumbnail.children('img');

.children仅遍历其直接孩子.wide-thumbnail.em-below

使用.find代替

$thumbnail.find('img');