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

时间:2016-05-17 06:11:19

标签: javascript html

只有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从121px增加到182px加班。例如,在3秒内慢慢放大。此刻它只是瞬间扩大。

7 个答案:

答案 0 :(得分:1)

你可以通过简单地添加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;
}

答案 1 :(得分:0)

您可以使用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。

答案 2 :(得分:0)

正如Nitsan Baleli评论的那样,您可以使用CSS过渡。此外,CSS还支持:悬停选择器,因此更容易做到这一点。

HTML:

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

CSS:

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

使用setInterval()clearInterval()

&#13;
&#13;
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";
}
&#13;
<div class="mid">
    <img onmouseover="lielaBilde(this)" onmouseout="mazaBilde(this)" src="http://placehold.it/121" alt="bilde" style="height:121px; width:121px"/>
</div>
&#13;
&#13;
&#13;

答案 5 :(得分:0)

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

1 - 您提供了错误的js文件路径。

2 - 您的功能位于head标记中。在这种情况下,您需要在body标记之后移动JavaScript,并查看here

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>

答案 6 :(得分:0)

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

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