我试图在鼠标悬停在元素上时将类添加到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;
答案 0 :(得分:2)
您需要调用CC.bindEvent()
来绑定事件处理程序。你的悬停功能需要切换类,而不是添加它,然后立即删除它。
img
元素不是$thumbnail
的子元素,它是孙子。使用.find()
代替.children()
。
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;
答案 1 :(得分:1)
问题在于此行,因为未捕获img
标记。
$thumbnail.children('img');
.children
仅遍历其直接孩子.wide-thumbnail.em-below
。
使用.find
代替
$thumbnail.find('img');