0

我有一些 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 片段:

$(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();
});


});

这根本行不通。有人对此有想法吗?提前致谢!

4

3 回答 3

2

是工作检查一下:

但是,您可以将代码减少到

$(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 类命名为图像类

<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。这可能是问题所在。

于 2013-07-03T09:58:32.677 回答
0

这样做:使用mouseenter()它有一个callback方法,例如。mouseleave()

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


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

小提琴

于 2013-07-03T10:00:21.040 回答
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
});
于 2013-07-03T09:59:47.130 回答