将鼠标悬停在另一个div中的文本和显示图像上,图像将保持不变



当有人将鼠标悬停在文本上时,我在尝试在另一个div中显示图像时遇到了很多问题。我有一个菜单,里面有5行文字。我想在相同的位置显示不同的图像,每次悬停在这些文本行上。我设法用CSS在悬停时显示图像,但它们在取消悬停时消失了。我希望在用户悬停在一个文本上之后,图像保持不变,然后当用户悬停在另一个文本时,相关图像显示在相同的位置。我也尝试了其他布局,但对设备大小没有反应。

这是我当前的代码:

<div class="parent">
<p style="padding-left: 320px;"><a href="link1"><strong>menuitem1</strong></a></p>
</div>
<div class="parent1">
<p style="padding-left: 320px;"><a href="link2"><strong>menuitem2</strong></a></p>
</div>
<div class="parent2">
<p style="padding-left: 320px;"><a href="link3"><strong>menuitem3</strong></a></p>
</div>
<div class="parent3">
<p style="padding-left: 320px;"><a href="link4"><strong>menuitem4</strong></a></p>
</div>
<div class="parent4">
<p style="padding-left: 320px;"><a href="link5"><strong>menuitem5</strong></a></p>
</div>
<h1 id="demo" onmouseover="mouseOver()" onmouseout="mouseOut()">Mouse 
over 
me</h1>
<span id="span" style="display:none;">Hey! Click me to close</span>
<script>
function mouseOver() {
document.getElementById("span").style.display = "block";
}
function mouseOut() {
}
window.onclick = function(event) {
if (event.target == span) {
span.style.display = "none";
}
}
</script>

如果我犯了什么错误,我很抱歉。我的技术知识不多。

实现这一点的唯一方法是使用JavaScript和mouseOver函数,将显示设置为none,一旦h1悬停在上面,它就会运行函数mouseOver(),该函数将span显示设置为block(可见)。您还可以在将类添加到跨度之后设置状态,这会使跨度在几秒钟后自动关闭。

function setURL(newUrl){
var url=newUrl;
return function(){
document.getElementById('picture').setAttribute('src',url);
}
}
document.getElementById('text1').addEventListener('mouseover',setURL('https://upload.wikimedia.org/wikipedia/commons/8/8f/Example_image.svg'));
document.getElementById('text2').addEventListener('mouseover',setURL('https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg'));

.container{
width:200px;
display:flex;
margin-left:auto;
margin-right:auto;
}
.container > div{
width:50%;
}
img{
width:30px;
height:30px;
}
<div class="container">
<div>
<p id="text1">picture1</p>
<p id="text2">picture2</p>
</div><!--END TEXT-->
<div>
<img id="picture" src="">
</div><!--END PICTURE-->
</div><!--END CONTAINER-->
PD_7

最新更新