当访客悬停图像时,会出现alt文字。是否有可能用JavaScript来模拟这种行为对于任何事件和元素?模拟图像alt属性的行为
在这一点附加一个小跨度将是一个解决方案,但我想知道如果这是可能的,而不追加任何内容。
当访客悬停图像时,会出现alt文字。是否有可能用JavaScript来模拟这种行为对于任何事件和元素?模拟图像alt属性的行为
在这一点附加一个小跨度将是一个解决方案,但我想知道如果这是可能的,而不追加任何内容。
一种选择可能是使用:before
或:after
伪元素描述here为了使CSS工具提示。
首先检查title属性,它与alt属性非常相似。 除此之外,这里还有类似mouseenter
和mouseleave
的活动。你甚至可以在元素上使用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>
下面是一个使用<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>
看一看的[标题](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/title)属性 – sharf
感谢您的回答。我想在画布中使用此功能并动态更改文本。 – tolga
_“但我想知道这是不可能的,但不会在内容中添加任何内容。”__参见http://stackoverflow.com/questions/33587727/caption-does-not-work-after-centering-image – guest271314