0

当鼠标移到图像上时,我想放大图像,然后将其恢复正常。使用我的 JavaScript 中的 getPhoto 函数可以正常大小地加载图像,但是当我将鼠标悬停在它上面时,什么也没有发生。

我究竟做错了什么?

document.getElementById("photo").onmouseover = function() {
  mouseOver()
};
document.getElementById("photo").onmouseout = function() {
  mouseOut()
};

function getPhoto(handle) {
  var img = new Image();
  var div = document.getElementById("photo");
  while (div.firstChild) {
    div.removeChild(div.firstChild);
  }
  img.src = "https://res.cloudinary.com/harmhxmnk/image/upload/" + handle;
  img.height = 32;
  img.onload = function() {
    div.appendChild(img);
  };
}

function mouseOver() {
  var img = document.getElementById("photo");
  img.height = 100;
}

function mouseOut() {
  // TODO
}
.photo {
  position: absolute;
  top: 86px;
  right: 92px;
}
<div class="photo" id="photo"></div>

4

4 回答 4

4

不需要 JS 恕我直言 :-)

.photo {
  position: absolute;
  top: 86px;
  right: 92px;
  transform: scale(1);
  transition: transform .5s;
}

.photo:hover {
  transform: scale(1.2);
}
<div class="photo" id="photo"><img src="https://wallpaperbrowse.com/media/images/3848765-wallpaper-images-download.jpg" /></div>

于 2018-12-19T13:55:37.567 回答
1

到目前为止,没有一个答案可以解释为什么它不起作用。它不起作用的原因是您在图像上设置了 32 的高度。但是当你设置高度时,你是在 div 上设置它,而不是在图像上。因此,如果您想按照自己的方式进行操作,则需要选择图像。querySelector 将让您引用元素中的图像。

function mouseOver() {
  var img = document.querySelector("#photo img");
  img.height = 100;
}
于 2018-12-19T14:11:25.770 回答
0

我认为只使用css会更容易和更干净

#photo:hover{
    height: 100:
}
于 2018-12-19T13:55:29.650 回答
0

使用 flexbox 的 CSS 非常简单(演示

.col {
  display: flex;
}

.col img {
  margin: 5px 5px; /* more margin makes the image smaller */
  flex-grow: 1;
}

.col img:hover {
  margin: 0 0; /* less margin on hover makes the image bigger */
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
    <div class="col">       
        <img src="https://placekitten.com/g/200/200">
    </div>
    <div class="col">
      <img src="https://placekitten.com/g/200/200">
    </div>
  </div>
  <div class="row">
    <div class="col">
      <img src="https://placekitten.com/g/200/200">
    </div>
    <div class="col">
      <img src="https://placekitten.com/g/200/200">
    </div>
    <div class="col">
      <img src="https://placekitten.com/g/200/200">
    </div>
  </div>  
</div>

于 2018-12-19T14:03:36.187 回答