首页 > 解决方案 > 用于隐藏图像和更改文本的 Javascript 不起作用

问题描述

这是我的代码:

我想在鼠标悬停时隐藏图像并且只显示文本。然后,当鼠标移开时,图像应该是可见的。text 属性工作正常,但 image 有问题。点击后完全消失。

function updated1(element){

document.getElementById("d1").innerHTML = "web deveopment and designing, html css js and bootstrap";
  document.getElementById("d1").style.borderRadius = "4.5%";
document.getElementById("imgd1").style.visibility = 'hidden';

}


function undod1(){
document.getElementById("d1").innerHTML = "WEB DEVELOPMENT";
  document.getElementById("d1").style.borderRadius = "0%";
document.getElementById("imgd1").style.visibility = 'visible';
  
}
#d1 {
  border: 1px solid;
  padding-top: 7px;
  text-align: center;
  box-shadow: 5px 10px #DBE0E3;
  margin-top: 3%;
  color: #FFFFFF;
  width: 350px;
  height: 350px;
  font-size: 40px;
  font-weight: bold;
  line-height: 70px;
  background-color: #DC3D3D;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <title> js</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>

<body>

  <div class="container">
    <div class="row">

      <section id="d1" class="col-md-4 col-md-push-4  col-xs-12" onmouseover="updated1(this)" onmouseleave="undod1()">
        <p>WEB DEVELOPMENT
          <p>
            <img id="imgd1" src="https://miro.medium.com/max/1200/1*pE2fOVDikEUwiQJlh4ggzg.jpeg" height="90%" width="90%">

      </section>
    </div>
  </div>
</body>

</html>

我在 CODEPEN 上的代码的链接在这里

标签: javascripthtmlcss

解决方案


你的问题是这部分

document.getElementById("d1").innerHTML = "...";

因为此代码从父级中删除所有子级并插入文本。所以基本上,当你的鼠标离开时,那里没有图像让它可见。您不需要那么多 Javastipt 来创建您想要的效果。更好的 HML,更多的 CSS 和更少的 JS:

<section
    id="d1"
    class="col-md-4 col-md-push-4 col-xs-12"
    onmouseover="updated1(this)"
    onmouseleave="undod1()"
>
    <p class="message">WEB DEVELOPMENT<p>
    <img id="imgd1" src="https://miro.medium.com/max/1200/1*pE2fOVDikEUwiQJlh4ggzg.jpeg" height="90%" width="90%">
</section>
#d1:hover {
  border-radius: 4.5%;
}

img {
  opacity: 1
}

#d1:hover img {
  opacity: 0
}
let message = "WEB DEVELOPMENT";
let parent = document.querySelector("#d1");
let item = document.querySelector(".message");
function updated1(element){
  item.innerText = "web deveopment and designing, html css js and bootstrap";
}

function undod1(){
  item.innerText = message;
}

如果您尝试做一些比您要求的更复杂的事情,请尝试添加/删除类以更改样式,而不是在 Javascript 中添加样式。这是更改样式的一种更简单、更简洁的方法。


推荐阅读