我正在尝试在我悬停图像时在图像上添加链接。 目前我的javascript如下:
// check elements mouse is hover
document.addEventListener("mouseover", addCropLink, true);
document.addEventListener("mouseout", removeCropLink, true);
// add link if element is image
function addCropLink(){
var target = event.target;
if (target instanceof HTMLImageElement){
var cropLink = document.createElement("a");
cropLink.setAttribute("class", "resizeMyPhoto");
cropLink.setAttribute("id", "resizeMyPhoto");
cropLink.setAttribute("target", "_blank");
cropLink.innerHTML += "Crop/Resize";
cropLink.href = chrome.extension.getURL("index.html#");
cropLink.href = cropLink.href + target.src;
target.parentNode.style.position = "relative";
target.parentNode.style.display = "inline-block";
target.parentNode.insertBefore(cropLink, target.nextSibling);
}
}
// remove link if element is image
function removeCropLink(){
var target = event.target;
if (target instanceof HTMLImageElement){
var cropLink = document.getElementById("resizeMyPhoto");
cropLink.parentNode.removeChild(cropLink);
}
}
问题是当用户试图点击链接时,他正在从图像中进行鼠标移除,并且正在删除链接。
有人可以建议解决方案吗?
编辑 使用mouseout / mouseleave并没有解决问题。
答案 0 :(得分:0)
好的,所以我改变了我的脚本,所以它根本不会在mosueleave / mouse上运行。 我正在查看鼠标所在的元素,如果他不在图像上或我创建的链接上,我将删除该链接。 这是带注释的完整javascript:
iconURL = chrome.extension.getURL("/icons/button-icon.png");
// check elements mouse is hover
document.addEventListener("mouseover", setLink, true);
// handles creating of the crop link
function setLink(){
var target = event.target;
if (target instanceof HTMLImageElement){
// make sure no links are visible
var cropLink = document.getElementById("resizeMyPhoto");
if (cropLink !== null){
cropLink.parentNode.removeChild(cropLink);
}
// create the link
else{
cropLink = document.createElement("a");
cropLink.setAttribute("class", "resizeMyPhoto");
cropLink.setAttribute("id", "resizeMyPhoto");
cropLink.setAttribute("target", "_blank");
cropLink.innerHTML += "Crop/Resize";
cropLink.href = chrome.extension.getURL("index.html#") + target.src;
target.parentNode.style.position = "relative";
target.parentNode.style.display = "inline-block";
target.parentNode.insertBefore(cropLink, target.nextSibling);
}
}
else{
var cropLink = document.getElementById("resizeMyPhoto");
// make sure mouse is not on link
if(target == cropLink || cropLink == null){
return;
}
// remove the link
else{
cropLink.parentNode.removeChild(cropLink);
}
}
}
希望这会对某人有所帮助......