2015-11-08 70 views
0

當訪客懸停圖像時,會出現alt文字。是否有可能用JavaScript來模擬這種行爲對於任何事件和元素?模擬圖像alt屬性的行爲

在這一點附加一個小跨度將是一個解決方案,但我想知道如果這是可能的,而不追加任何內容。

enter image description here

+0

看一看的[標題](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/title)屬性 – sharf

+0

感謝您的回答。我想在畫布中使用此功能並動態更改文本。 – tolga

+0

_「但我想知道這是不可能的,但不會在內容中添加任何內容。」__參見http://stackoverflow.com/questions/33587727/caption-does-not-work-after-centering-image – guest271314

回答

0

一種選擇可能是使用:before:after僞元素描述here爲了使CSS工具提示。

1

首先檢查title屬性,它與alt屬性非常相似。 除此之外,這裏還有類似mouseentermouseleave的活動。你甚至可以在元素上使用data-alt屬性提供的數據(你可以用任何東西代替alt)。

也有很多這樣的圖書館,但我會告訴你一個快點。

(function(){NodeList.prototype.forEach = Array.prototype.forEach; 
 

 
var toolTip = document.createElement('DIV'); 
 
toolTip.style.display = "none"; 
 
toolTip.style.position = "absolute"; 
 
toolTip.style.width = "50px"; 
 
toolTip.style.height = "auto"; 
 
toolTip.style.border = "solid 1px black"; 
 
toolTip.style.transition = "top 50ms,left 50ms, display 500ms"; 
 
    function updatePosition(e){ 
 
     toolTip.style.top = e.clientY + "px"; 
 
     toolTip.style.left = e.clientX + "px"; 
 
    } 
 
document.body.appendChild(toolTip); 
 
document.querySelectorAll("[data-alt]").forEach(function(e){ 
 
    e.addEventListener('mouseenter',function(e){ 
 
    toolTip.style.display = "block"; 
 
    toolTip.style.cursor = "text"; 
 
    toolTip.style.top = e.clientY + "px"; 
 
    toolTip.style.left = e.clientX + "px"; 
 
    toolTip.textContent = this.getAttribute('data-alt'); 
 
    }) 
 
}) 
 
document.querySelectorAll("[data-alt]").forEach(function(e){ 
 

 
    e.addEventListener('mousemove',function(e){  
 
     updatePosition(e) 
 

 
    }) 
 
}) 
 
document.querySelectorAll("[data-alt]").forEach(function(e){ 
 
    e.addEventListener('mouseleave',function(e){ 
 
    toolTip.style.display = "none"; 
 
    }) 
 
}) 
 
})();
<h2 class="space" data-alt="Hello">Your Answer</h2>

2

下面是一個使用<figcaption>發揮你的懸停提示的作用,一個解決方案。

使用<figcaption>作爲工具提示將爲您的標記提供額外的語義含義。

figure.inline-image, 
 
figure.inline-image img { 
 
display: inline-block; 
 
width: 260px; 
 
height: 150px; 
 
background-color: rgba(0, 0, 0, 1); 
 
} 
 

 
figcaption { 
 
display: none; 
 
position: relative; 
 
top: -70px; 
 
left: 40px; 
 
padding: 3px; 
 
width: auto; 
 
border: 1px solid rgba(0, 0, 0, 1); 
 
background-color: rgba(255, 255, 227, 1); 
 
font-size: 12px; 
 
} 
 

 
figure.inline-image:hover figcaption { 
 
display: inline-block; 
 
}
<figure class="inline-image"> 
 
<img src="danish-flag.jpg" alt="Flag of Denmark" /> 
 
<figcaption>In the sky flies a red flag with a white cross whose vertical bar is shifted towards the flagpole.</figcaption> 
 
</figure>