2013-07-03 58 views
0

我有一些javascript的问题。我想徘徊的图像时显示一个div:jQuery show()隐藏()鼠标在图像上

 <div class="slideshow"> 
      <img src="img/picture1.jpg" id="picture1" /> 
      <img src="img/picture2.jpg" id="picture2" /> 
     </div> 

     <div class="pic1desc"> 
       <h3>Headline</h3><br /> 
       Text 
     </div> 

     <div class="pic2desc"> 
       <h3>Headline</h3><br /> 
       Text 
     </div> 

这里是我的JavaScript的代码片段:

$(document).ready(function() { 
$('.pic1desc').hide(); 
$('.pic2desc').hide(); 

//When the Image is hovered upon, show the hidden div using Mouseover 
$('#picture1').mouseover(function() { 
$('.pic1desc').show(); 
}); 

//When the Image is hovered away from, hide the div using Mouseout 
$('#picture1').mouseout(function() { 
$('.pic1desc').hide(); 
}); 


}); 

这是不工作的。有人有这个想法吗?提前致谢!

+0

包括jQuery的? – MrCode

+0

这是工作正常见控制台错误,如果这不起作用,可能会有其他错误 – Raghurocks

+0

可能你忘了包括jQuery脚本? –

回答

2

这是工作检查了这一点..

fiddle

但是你可以减少你的代码

$(document).ready(function() { 
$('.pic1desc','.pic2desc').hide(); 


//When the Image is hovered upon, show the hidden div using Mouseover 
$('#picture1').hover(function() { 
    $('.pic1desc').show(); 
},function() { 
    $('.pic1desc').hide(); 
}); 

//same for `#picture2` 

OR

名字你的div类,图像类

<div class="picture1"> 
      <h3>Headline</h3><br /> 
      Text 
    </div> 

    <div class="picture2"> 
      <h3>Headline</h3><br /> 
      Text 
    </div> 

    $(document).ready(function() { 
    $('.picture1','.picture2').hide(); 


//When the Image is hovered upon, show the hidden div using Mouseover 
$('img[id^="picture"]').hover(function() { 
    $('.'+ $(this).prop('class')).show(); 
},function() { 
    $('.'+ $(this).prop('class')).hide(); 
}); 

这是动态的,适用于任何数量的元素...

和是确保你正在装载(含)jquery.js..that可能是问题..

+0

谢谢 - 我已经加载了一个depricated jquery版本:/我想我需要更多的咖啡! – Dublay

+0

欢迎..很高兴它帮助.. – bipen

0

怎么样像thise:

$(document).on('mouseover mouseout', '#picture1', function(){ 
    // By giving this function two triggers, the same action is performed for each trigger 
    $('.pic1desc').toggle(); 
}); 

或者:

$(document).on('mouseenter mouseleave', '#picture1', function(){ 
    // By giving this function two triggers, the same action is performed for each trigger 
    $('.pic1desc').toggle(); 
}); 

另一种解决方案可能是这个(如果你想先进的行动发生):

$('#picture1').on('mouseover', function(){ 
    // something on mouseover 
    // this way you get more space for larger/more special actions 
)}.bind('mouseout', function(){ 
    // something on mouseout 
    // Same space for mouseout 
}); 
+1

'生活()'是在jQuery中自1.8版本中删除 –

+1

谢谢,修复它:)仍然习惯on(),一直使用live()一段时间 – Martijn

0

这样做:用mouseenter()它具有callback方法如。 mouseleave()

$('#picture1').mouseenter(function() { 
    $('.pic1desc').show(); 
}).mouseleave(function(){ 
    $('.pic1desc').hide();  
}); 


$('#picture2').mouseenter(function() { 
    $('.pic2desc').show(); 
}).mouseleave(function(){ 
    $('.pic2desc').hide();  
}); 

Fiddle