我正在使用 bootstrap 对我的网站进行编码(以使其具有响应性,并且对我来说更容易更新)并且我希望在我浏览文本时显示图像。 这是代码:
<div class="row">
<div class="col-sm-8" style="font-size: 24pt">
<a href=""> INSTITUT HENRI POINCARRE, POSTER — 2017</a>
</div>
<div class="col">
<img src="image/ihp_poster01.JPG" class="img-fluid" alt="Responsive image">
</div>
</div>
我希望在悬停“INSTITUT HENRI POINCARRE, POSTER — 2017”时显示 ihp_poster01.JPG 图像。我已经尝试了很多没有用的东西,因为 img 和文本不在同一个 <div>
.
我想我必须使用 Javascript,但我没有找到任何 JS:/
有人可以帮助我吗?
谢谢
最佳答案
您可以在 text
上使用 mouseenter
和 mouseleave
事件(当然使用 JavaScript)并切换 显示
image
相应的样式...
window.onload = function() {
var name = document.getElementById("name");
var image = document.getElementById("img");
name.addEventListener("mouseenter", function( event ) {
image.style.display = "block";
});
name.addEventListener("mouseleave", function( event ) {
image.style.display = "none";
});
}
<div class="row">
<div class="col-sm-8" style="font-size: 24pt">
<a href="" id="name"> INSTITUT HENRI POINCARRE, POSTER — 2017</a>
</div>
<div class="col">
<img style="display:none;" id="img" src="image/ihp_poster01.JPG" class="img-fluid" alt="Responsive image">
</div>
</div>
更新:为了使这个动态化并处理不同的文本和不同的图像,可以使用具有通用 JS 函数的 onmouseenter
和 onmouseleave
,有一个请看下面的片段:
function toggleShow(elementId) {
let el = document.getElementById(elementId);
el.style.display = "block";
}
function toggleHide(elementId) {
let el = document.getElementById(elementId);
el.style.display = "none";
}
<div class="row">
<div class="col-sm-8" style="font-size: 24pt">
<a href="" onmouseenter="toggleShow('image1');" onmouseleave="toggleHide('image1');"> INSTITUT HENRI POINCARRE, POSTER — 2017</a>
</div>
<div class="col">
<img style="display:none;" id="image1" src="image/ihp_poster01.JPG" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="row">
<div class="col-sm-8" style="font-size: 24pt">
<a href="" onmouseenter="toggleShow('image2');" onmouseleave="toggleHide('image2');"> INSTITUT HENRI POINCARRE, POSTER — 2017</a>
</div>
<div class="col">
<img style="display:none;" id="image2" src="image/ihp_poster01.JPG" class="img-fluid" alt="Responsive image">
</div>
</div>
关于javascript - 悬停文本时出现图像(html bootstrap),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51232278/