javascript - 如何使用setInterval放大图像

标签 javascript html css

我想实现当点击一个图像然后它会放大一段设定的时间。到目前为止,我在我的 JS 中已经完成了,但它不起作用

 var image =  document.getElementById('pic');

function enlarge() {
    image.style.height="600px";
}

image.onclick =enlarge;

在我尝试实现之后。

 var image =  document.getElementById('pic');

function enlarge() {
    image.style.height="600px";
}

image.onclick = setInterval(enlarge; 1000);

我应该如何实现? JSFIDDLE

最佳答案

使用设置间隔

我们想要 60fps,所以每帧将是 1000/60,大约等于 16.667ms 长。我们需要将高度扩大500px。 500/60 等于 8.334。所以我们需要一个 16.667 毫秒的间隔,并且每次迭代,将图像放大 8.334px,并在高度达到 600px 时停止:

var images = document.querySelectorAll('.pic');

images.forEach(function(image) {
  image.addEventListener('click', enlarge);
});

function enlarge(e) {
  var image = e.target;
  var interval;
  var height = 100;
  
  interval = setInterval(function() {
    height += 8.334;
    
    if(height >= 600) {
      height = 600;
      clearInterval(interval);
    }
    
    image.style.height = height + 'px';
  }, 16.667);
}
.pic {
  width: 100px;
  height: 100px;
  vertical-align: top;
}
<img src='https://placehold.it/100x100' class='pic'>
<img src='https://placehold.it/100x100' class='pic'>


使用requestAnimationFrame

更好的方法是使用 requestAnimationFrame()产生更流畅的动画。根据 MDN:

The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.

数学保持不变,但 requestAnimationFrame 将在 16.667 毫秒后处理调用下一帧。

var images = document.querySelectorAll('.pic');

images.forEach(function(image) {
  image.addEventListener('click', enlarge);
});

function enlarge(e) {
  var image = e.target;
  var interval;
  var height = 100;
  
  function enlargeInner() {
    height += 8.334;
    
    if(height >= 600) {
      height = 600;
    }
    
    image.style.height = height + 'px';
    
    height < 600 && requestAnimationFrame(enlargeInner);
  }
  
  enlargeInner();
}
.pic {
  width: 100px;
  height: 100px;
  vertical-align: top;
}
<img src='https://placehold.it/100x100' class='pic'>
<img src='https://placehold.it/100x100' class='pic'>

关于javascript - 如何使用setInterval放大图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41201721/

相关文章:

javascript - 在午夜重置变量/计数器的循环函数(moment.js,node.js)

python - 使用 Python 清理刮取的文本字符串

html - Twitter Bootstrap 3.0 - 居中搜索框

JavaScript/jQuery 毕业去饱和十六进制颜色

javascript - 具有多个值的 JQuery 多选

javascript 字符串正则表达式(css有效性检查+转换)

Javascript - 从数值创建金字塔数组

javascript - 我可以使用子字符串过滤javascript中的对象数组吗?

javascript - $(document).ready(function() 和 $(function() 之间有什么区别?

javascript - 显示随机 div javascript,有时只显示 div