【发布时间】:2016-12-08 22:54:33
【问题描述】:
我有一个针对多个图像的悬停方法,当您悬停图像时,它应该只在该悬停图像上添加一个预览图标,但它发生在每个元素上,我是 Javascript/jQuery 的新手,不能找个方法,谁能帮帮我?
这是我的实际 jQuery 代码:
// Make images smaller
$('.card').find('p > img').css({
'width': '160px',
'height': '118px'
}).parent().css('text-align', 'center');
// Add preview icon into DOM
$('.card').find('p:last-child').prepend("<img class='preview-icon' src='http://www.iconsfind.com/wp-content/uploads/2015/11/20151116_564931d273df6.png' width='80' height='80' />");
// Add style to our preview image
$('.preview-icon').css({
'position' : 'absolute',
'z-index' : '99999',
'left' : '50%',
'top' : '50%',
'bottom' : 'auto',
'right' : 'auto',
'transform' : 'translateX(-50%) translateY(-50%)'
}).hide();
// On hover add/remove style
$('.card').find('p > img').hover(function() {
$('.card').find('p > img').css({
'opacity' : .2,
'transition' : 'all 0.2s',
'-webkit-transition' : 'all 0.2s',
'cursor' : 'pointer'
});
$('.preview-icon').show();
}, function() {
$('.card').find('p > img').css({
'opacity' : 1,
});
$('.preview-icon').hide();
});
更新 v1
所以现在它正在工作,但是如果您将鼠标悬停在图像上,然后将鼠标悬停在出现的预览图标上,它不会绑定图像,它们就像两个不同的图像一样工作(尝试使用上面网站内的 Chrome 开发工具的代码):
// Make images smaller
$('.card').find('p > img').css({
'width': '160px',
'height': '118px'
}).parent().css('text-align', 'center');
// Add preview icon into DOM
$('.card').find('p:last-child').prepend("<img class='preview-icon' src='http://www.iconsfind.com/wp-content/uploads/2015/11/20151116_564931d273df6.png' width='80' height='80' />");
// Add style to our preview image
$('.preview-icon').css({
'position' : 'absolute',
'z-index' : '99999',
'left' : '50%',
'top' : '50%',
'bottom' : 'auto',
'right' : 'auto',
'transform' : 'translateX(-50%) translateY(-50%)'
}).hide();
// On hover add/remove style
$('.card').find('p > img').hover(function() {
$(this).css({
'opacity' : .2,
'transition' : 'all 0.2s',
'-webkit-transition' : 'all 0.2s',
'cursor' : 'pointer'
});
$(this).closest('.card').find('.preview-icon').show();
}, function() {
$(this).css({
'opacity' : 1
});
$(this).closest('.card').find('.preview-icon').hide();
});
谢谢!
【问题讨论】:
标签: jquery jquery-hover