[英]Alternative for img:[alt]hover:after
我是新手编码员。 我正在使用WordPress模板(Semplice)来帮助建立我的新网站。
我想要的行为是将鼠标悬停在图像上,并显示自定义的文本。 我相信我可以使用工具提示或HTML5伪选择器来做到这一点。
我可以将自定义CSS以及JavaScript添加到主题中。 我还可以将自定义类添加到我上传的图像中。 所以我认为我在CSS中的方法是:
.this-is-a-custom-class img[alt]:hover:after {
content: attr(alt);
position: absolute;
top:-100%;
left:0%;
}
但是当我四处挖掘时,这些伪选择器似乎不适用于图像?
考虑到我只能为图像添加自己的自定义CSS,JavaScript和自定义类,因此有人可以提出解决方法吗?
https://codepen.io/anon/pen/jxqadW :这能回答您的问题吗? 如果没有,告诉我
如果您在理解代码时遇到问题,请随时向我提问。
HTML:
<div id="container">
<img id="image" src= "https://picsum.photos/200/300"/>
<div id="information">
Hello there
</div>
</div>
CSS:
#container{
width:200px;
position:relative;
}
#image{
max-width:100%;
}
#information{
position:absolute;
top:10px;
display:none;
}
JS:
document.getElementById("image").onmouseover=function(){
document.getElementById("information").style.display="inline";
}
document.getElementById("image").onmouseleave=function(){
document.getElementById("information").style.display="none";
}
这是一个简单的解决方案:
$(function() { //get all images at detach them from the document; you can change this class name var allImages = $('.image-class').detach(); //create the mark up pattern allImages = createMarkup(allImages); //add new mark up back to the document allImages.each(function(index, element) { $('.container').append(element); }) function createMarkup(images) { var container = []; images.each(function(index, element) { var imageContainer = $('<div class="img-container"></div>'); var imageText = $('<p class="img-container__text"></p>') imageText.text($(element).attr('alt')); imageContainer.append(element, imageText); container.push(imageContainer); }); return $(container); } });
.img-container { width: 300px; text-align: center; position: relative; margin: 100px auto; } .img-container__text { display: none; position: absolute; top: -100px; left: 0; } .img-container__img { width: 100%; } .img-container:hover>.img-container__text { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <img class="image-class" src="https://www.mozilla.org/media/img/home/dino.d3d01561e288.svg" alt="Hello"> </div>
它通过在页面加载时使用jQuery动态更改标记并在作为图像父级的div
上设置悬停状态来工作。 在同一个包含div
元素中,我包含了要在图像悬停时要显示的文本的子元素,其显示属性为none。
当容器悬停在上方时,保存文本的元素将获得显示值block。
您想要的方式将无法使用,因为图像已替换元素,并且:: before和:: after伪元素仅适用于未替换的元素
根据MDN网站文档 :
:: before和:: after生成的伪元素包含在元素的格式框中,因此不适用于替换的元素,例如或
元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.