我举了一个例子来帮助解释这个问题:http://codepen.io/tathianactn/pen/EaEzRB .
在这个例子中,我有一个 map 和 map 上的各种标记(蓝色方 block )。当您将鼠标悬停在标记上时,工具提示应该会出现,其中包含图像(左)和一些文本(右)。图像和文本 div 应始终具有相同的高度,因此我使用 javascript 来确定最高的 div,并将该高度值分配给较短的 div。
最初,工具提示 div 被标记为“显示:无;”,然后当您将鼠标悬停在标记上时它“淡入”,当您悬停在标记上时它“淡出”。
我已经一步一步地测试了这段代码,在我添加淡入/淡出 Action 之前,一切都正常工作。在添加这两个 Action 之前,javascript 调整大小工作正常(您可以尝试删除这两行以查看),但是当我添加这些淡入淡出 Action 时,高度停止正常工作。
我注意到,如果您快速将鼠标悬停然后又悬停在同一个标记上,高度调整确实会生效。
有什么想法吗?我在调整大小后添加了淡入淡出,假设所有调整大小都会在工具提示显示之前完成,但肯定有些地方无法正常工作。
如果有任何帮助,我将不胜感激。谢谢!
$('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');
});
最佳答案
这里的问题是 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
元素会呈现在页面上,您可以获得它的高度.
关于javascript - Fadein 和 Fadeout 阻止 jquery 函数正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28640016/