Javascript 没有第二个图像可用时,jQuery悬停不起作用
所以我有图像容器的块,一旦我悬停在任何一个容器上,悬停就开始工作了。但是当悬停图像不可用时,图像就会闪烁。下面是我的代码:Javascript 没有第二个图像可用时,jQuery悬停不起作用,javascript,jquery,Javascript,Jquery,所以我有图像容器的块,一旦我悬停在任何一个容器上,悬停就开始工作了。但是当悬停图像不可用时,图像就会闪烁。下面是我的代码: if($('.clp hover img[data src!=“null”])){ var tempSrc=''; $(“.clp hover img”).hover(函数(){ tempSrc=$(this.attr('src'); $(this.attr(“src”),$(this.data(“src”); },函数(){ $(this.attr(“src”,tempS
if($('.clp hover img[data src!=“null”])){
var tempSrc='';
$(“.clp hover img”).hover(函数(){
tempSrc=$(this.attr('src');
$(this.attr(“src”),$(this.data(“src”);
},函数(){
$(this.attr(“src”,tempSrc);
});
}
img{
宽度:200px;
高度:自动;
}
问题是因为您的
if
语句正在查看jQuery对象,因此总是返回true
。因此,事件将应用于所有元素
您可以通过删除if
条件并使用属性选择器仅选择具有有效值的data
属性的元素来修复此问题并改进逻辑。还请注意,应避免使用全局变量,在这种情况下,您可以通过使用另一个data
属性来保存src
,以便在mouseleave
事件发生时用于图像。试试这个:
$('.clp hover img[data hover src!=“null”])。hover(function(){
$(this.attr('src',function()){
返回$(this.data('hover-src'))
})
},函数(){
$(this.attr('src',function()){
返回$(this.data('src'))
})
});代码>
img{
宽度:200px;
高度:自动;
}
@kirantesting我添加了一个替代解决方案,它不改变HTML,但仍然避免了全局变量First解决方案不起作用,不确定。第二个对我有用。非常感谢静态src是做什么的?在使用swatch更改产品颜色后,我注意到一些奇怪的问题,然后新产品在加载时显示正确的图像(ajax)。一旦鼠标退出,它就会显示与之前相同的图像(在选择样本之前,在悬停之前)。嘿,Rory,很抱歉打扰你。你能看一下吗?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">
<img class="tile-image clp-hover-img" alt="Cotton Sateen Bottom Sheet" title="Cotton Sateen Bottom Sheet"
itemprop="image" data-src="https://images.pexels.com/photos/1640769/pexels-photo-1640769.jpeg"
src="https://images.pexels.com/photos/735621/pexels-photo-735621.jpeg">
</div>
<div class="two">
<img class="tile-image clp-hover-img" alt="Cotton Sateen Bottom Sheet" title="Cotton Sateen Bottom Sheet"
itemprop="image" data-src="null" src="https://images.pexels.com/photos/1640769/pexels-photo-1640769.jpeg">
</div>
<div class="three">
<img class="tile-image clp-hover-img" alt="Cotton Sateen Bottom Sheet" title="Cotton Sateen Bottom Sheet"
itemprop="image" data-src="null" src="https://images.pexels.com/photos/1890420/pexels-photo-1890420.jpeg">
</div>