我有一些javascript的问题。我想在悬停图像时显示div:
<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-snippet:
$(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 :(得分:2)
This正在检查这个:
但是,您可以将代码缩减为
$(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`
或强>
将您的div类命名为image class
<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 。这可能是问题所在。
答案 1 :(得分:0)
这样的事情怎么样:
$(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
});
答案 2 :(得分:0)
这样做:使用mouseenter()
它有callback
方法,例如。 mouseleave()
$('#picture1').mouseenter(function() {
$('.pic1desc').show();
}).mouseleave(function(){
$('.pic1desc').hide();
});
$('#picture2').mouseenter(function() {
$('.pic2desc').show();
}).mouseleave(function(){
$('.pic2desc').hide();
});