我制作了一个图像预览器,当您将鼠标悬停在该链接上时,它会弹出图像。它有效,但有时当我停止将鼠标悬停在链接上时,它会无法 .empty
div。我偶尔会得到上一张图片、错误文本或两张图片。如果我再次悬停它是固定的。这种情况可能发生在 10% 的时间内。我也无法获得div的高度。不知道这个是不是也有关系。
$('<div/>',{
'id' : 'popup'
}).appendTo('body');
function showError() {
$('<div/>').text('Picture Not Found').appendTo('#popup');
$('#popup').show();
};
function getImage() {
$.ajax({
type: 'GET',
url: link,
error: function(){
showError();
},
success: function(data) {
var styleText = $('style', data).text();
var imageRegex = /background-image: url\('[^']+/;
var imageMatch = styleText.match(imageRegex);
if (imageMatch) {
var image = imageMatch[0].replace(/background-image: url\('/, '');
$('#popup').append('<img src="' + image + '" style="padding:0px" alt="">');
} else {
showError();
};
}
});
};
$('a').filter(function() {
return /users\/\d+\/pictures/.test(this.href);
}).removeAttr('title').hover(function(e) {
link = this.href.replace('http://', 'https://');
getImage();
$('#popup').show();
height = $('#popup').outerHeight();
console.log(height);
}, function() {
$('#popup').empty().hide();
})
});
最佳答案
看起来这是在快速通过链接时触发悬停事件的问题。似乎可以通过为悬停添加延迟来解决。
这是一个指向帮助指南的链接。 http://jelaniharris.com/2008/adding-a-delay-to-jquery-functions/
我还将它更改为用于错误消息的单独 div,这样我就可以更改图像的 src 而不是清空 div。我认为这会使它更快一些。
关于javascript - 当 div 清空时,Ajax 加载的弹出图像并不总是清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28207103/