基本上我想循环浏览html并获取所有图片并在悬停时叠加一个小按钮,所以当用户点击该按钮时,会出现一堆关于该图片的信息。现在我可以在照片上叠加一个小图标,点击它时会生成弹出窗口,但我不知道如何在悬停时动态添加所有照片上的图标。这就是我到目前为止所做的http://jsfiddle.net/s5sp1h6e/1/
//Getting all the images
function getAllImages()
{
var images = document.getElementsByTagName('img');
var srcList = [];
for(var i = 0; i < images.length; i++)
{
srcList.push(images[i].src);
}
}
I've found a script that overlays a image over all images but every time i'm changing the size of the image i'm overlaying, the script stops working and i can't understand why.
如果我想在此行中更改硬编码的宽度和高度,脚本将停止工作。
var overlay = $('<img class="protectionOverlay" src="' + overlayImg + '" width="' + img.width() + '" height="' + img.height() + '"/>') bla bla..
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function()
{
var overlayImg = 'http://www.privdog.com/PrivDog/logo-medium.png';
var useOnAllImages = true;
// Preload the pixel
var preload = new Image();
preload.src = overlayImg;
$('img').on('mouseenter touchstart', function(e)
{
// Only execute if this is not an overlay or skipped
var img = $(this);
if (img.hasClass('protectionOverlay')) return;
if (!useOnAllImages && !img.hasClass('protectMe')) return; // The script will be applied to all images. IF u don't want this -> useOnAllImages = false and class="protectMe"
// Get the real image's position, add an overlay
var pos = img.offset();
//var xx = overlayImg.offset();
//alert(xx.top);
var overlay = $('<img class="protectionOverlay" src="' + overlayImg + '" width="' + img.width() + '" height="' + img.height() + '"/>').css({position: 'absolute', zIndex: 9999999, left: pos.left, top: pos.top}).appendTo('body').bind('mouseleave', function()
{
setTimeout(function(){ overlay.remove(); }, 0, $(this));
});
if ('ontouchstart' in window) $(document).one('touchend', function(){ setTimeout(function(){ overlay.remove(); }, 0, overlay); });
});
}
答案 0 :(得分:0)
基本上你需要为mouseover和mouseout添加一个事件处理程序。在处理程序中对图像应用必要的更改。
$("img").on("mouseover", function () {
$(this).addClass("overlay-class");
var icon = $("<span class='icon' />").appendTo(document.body);
// logic to position the icon
}).on("mouseout", function () {
$(this).removeClass("overlay-class");
$(".icon").remove();
});