【问题标题】:Fadein and Fadeout stopping jquery function from working correctlyFadein 和 Fadeout 阻止 jquery 函数正常工作
【发布时间】:2015-02-21 07:50:31
【问题描述】:

我整理了一个示例来帮助解释这个问题:http://codepen.io/tathianactn/pen/EaEzRB

在这个例子中,我有一个地图和地图上的各种标记(蓝色方块)。当您将鼠标悬停在标记上时,应该会出现一个带有图像(左)和一些文本(右)的工具提示。图像和文本 div 应该始终具有相同的高度,因此我使用 javascript 来确定最高的 div,并将该高度值分配给较短的 div。

最初,工具提示 div 被标记为“display: none;”,然后当您将鼠标悬停在标记上时它会“淡入”,当您将鼠标悬停在标记上时它会“淡出”。

我已经逐步测试了这段代码,并且在我添加淡入/淡出动作之前一切正常。在添加这两个动作之前,javascript 重新调整大小工作得很好(您可以尝试删除这两行来查看),但是当我添加这些淡入淡出动作时,高度停止正常工作。

我注意到,如果您快速将鼠标悬停在同一标记上,然后再将鼠标悬停在同一标记上,则高度调整大小确实会生效。

有什么想法吗?我在调整大小后添加了淡入淡出,假设所有调整大小都会在工具提示出现之前完成,但肯定有一些东西不能正常工作。

如果有任何帮助,我将不胜感激。谢谢!

$('a.map_marker').hover(function(e) {

   //Change tooltip content based on location of marker clicked
   var elementToGet = '.tooltip_html_source.'+$(this).attr('location');
   var newHTML = $(elementToGet).html();
   $('#tooltip_container .tooltip_content').html(newHTML);

   //Get height of text div
   var textHeight = $('#tooltip_container .tooltip_content .text').height();

   //If text div is less than 70px (min height of image div)
   if(textHeight < 70) {

      //Then make the height of the text div = 70px
      $('#tooltip_container .tooltip_content .text').height(70);
   }

   // else if the text div is greater than 70px
   else if(textHeight > 70) {

      //Make the height of the image div = the height of the text div
      $('#tooltip_container .tooltip_content .image').height(textHeight);
   }

   //Once the resizing has been done, fade in the tooltip div
   $('#tooltip_container').fadeIn('slow');

}, function() {

   //On hover off, fade out the tooltip div
   $('#tooltip_container').fadeOut('slow');
});

【问题讨论】:

    标签: javascript jquery css fadein fadeout


    【解决方案1】:

    这里的问题是width & height of invisible elements(即具有display CSS 属性设置为none 的元素)未定义。

    因为您的#tooltip_container 确实具有display: none; 样式,所以在以某种方式在页面上显示它之前,您无法获得它的实际高度,例如通过将display 设置为block。但是有一个技巧:在你开始你的淡入淡出序列之前,你可以让它有效地不可见——要么将opacity 设置为0,要么添加visibility: hidden; 样式。

    解决您的问题的直接方法是将 fadeIn 动画向上移动 - 在您开始测量您正在褪色的元素之前:

    // Start fading the element
    $('#tooltip_container').fadeIn('slow');
    
    //Get height of text div
    var textHeight = $('#tooltip_container .tooltip_content .text').height();
    
    //If text div is less than 70px (min height of image div)
    if(textHeight < 70) ...
    
    // Rest of the code follows
    

    (完整代码:http://codepen.io/anon/pen/ogqrQo

    之所以起作用是因为fadeIn 立即将display 设置为block/inline/inline-block,同时将不透明度设置为0.0(并逐渐增加它)-因此您的#tooltip_container 元素在页面上渲染,你可以得到它的高度。

    【讨论】:

    • 优秀的@NikitaBaksalya!这与我放在一起的示例代码和我正在处理的实际项目完美配合。感谢您提供解决方案,尤其是您花时间解释“为什么”。非常感谢!
    猜你喜欢
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多