我想实现当点击一个图像然后它会放大一段设定的时间。到目前为止,我在我的 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/