如何使用javascript onmouseover缓慢放大图像

How to slowly enlarge image with javascript onmouseover

本文关键字:放大 图像 缓慢 onmouseover 何使用 javascript      更新时间:2023-09-26

只有Javascript,没有jQuery!

HTML:

<div class="mid">
    <img onmouseover="lielaBilde(this)" onmouseout="mazaBilde(this)" src="bilde.png" alt="bilde"/>
</div>

JS:

function lielaBilde(x) {
x.style.height = "121px";
x.style.width = "181px";
}
function mazaBilde(x) {
x.style.height = "121px";
x.style.width = "121px";
}

我想创建这样我的img从121像素增加到182像素。例如,在3秒钟内慢慢放大。现在它只是瞬间放大。

只需添加css即可完成,无需添加任何javascript或jQuery。

.mid{
 width: 300px;
 height: 300px;
 background: #222;
 -webkit-transition: width 2s ease, height 2s ease;
 -moz-transition: width 2s ease, height 2s ease;
 -o-transition: width 2s ease, height 2s ease;
 -ms-transition: width 2s ease, height 2s ease;
 transition: width 2s ease, height 2s ease;
}
.mid:hover {
 width: 121px;
 height: 181px;
}

您可以使用如下所示的CSS。

.mid img {
    width: 100px;
    height: 100px;
    -webkit-transition: width 2s, height 2s;
    transition: width 2s, height 2s
}
.mid img:hover {
    width: 181px;
    height: 181px;
}

不需要Javascript。

function lielaBilde(x) {
var pos=121;
 var id = setInterval(frame, 3);
 function frame() {
    if (pos == 181) {
      clearInterval(id);
    } else {
      pos++; 
      x.style.height= pos + 'px'; 
      x.style.width= pos + 'px'; 
    }
  }
}

试试这个鼠标悬停。纯javascript

正如Nitsan Baleli所评论的,您可以使用CSS转换。此外,CSS还支持:悬停选择器,这样做就更容易了

HTML:

<div class="mid>
    <img src="bilde.png" alt="bilde"/>
</div>

CSS:

div.mid img:hover {
   transform: scale(1.1);
}

使用setInterval()clearInterval()

function lielaBilde(x) {
  var height, width;
  myVar = setInterval(function(){
    height = parseInt(x.style.height);
    width = parseInt(x.style.width)+1;
    x.style.height = height + "px";
    x.style.width = width + "px";
    if(width==181)
      clearInterval(myVar);
  }, 50);
  
}
function mazaBilde(x) {
  clearInterval(myVar);
  x.style.height = "121px";
  x.style.width = "121px";
}
<div class="mid">
    <img onmouseover="lielaBilde(this)" onmouseout="mazaBilde(this)" src="http://placehold.it/121" alt="bilde" style="height:121px; width:121px"/>
</div>

您可以在函数中设置css3属性。。。

function lielaBilde(x) {
x.style.WebkitTransition = 'width 3s ease';
x.style.MozTransition = 'width 3s ease';
x.style.height = "121px";
x.style.width = "181px";
}

它正在工作。。。所以可能是你的功能不起作用,因为

1-你给出了错误的js文件路径。

2-您的函数位于head标记中。在这种情况下,您需要在body标记后移动JavaScript,请参阅此处

function lielaBilde(x) {
  x.style.height = "121px";
  x.style.width = "181px";
}
function mazaBilde(x) {
  x.style.height = "121px";
  x.style.width = "121px";
}
<div class="mid">
  <img onmouseover="lielaBilde(this)" onmouseout="mazaBilde(this)" src="http://placehold.it/121x121" alt="bilde" />
</div>