用JavaScript实现图片缓慢缩放效果

本文介绍了如何使用JavaScript实现点击按钮后图片逐渐缩放的效果。通过设置setInterval定时器,循环执行缩放操作,当图片达到特定尺寸时停止缩放。示例代码中展示了关键的JavaScript实现和页面布局技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(本文是慕课网课程文档整理,课程地址http://www.imooc.com/learn/80)

实现效果:


点击放大/减小按钮,图片进行相应的缩放,缩放到一定尺寸,不再缩放。(图片来自百度)

实现:

图片缓慢缩放,在一定程度上可以看做循环运行某段函数,因此,利用setInterval()定时器实现。

页面代码:

<span style="white-space:pre">	</span><div class = "content">
		<img src = "test.jpg" id = "img">
		<div>
		  <input type="button" id = "max" value = "放大">
		  <input type="button" id = "min" value = "减小">
		</div>
	<div>

居中利用margin:auto,但是不要忘了设置宽度。

js实现:

利用setInterval定时器来操作。

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta charset="utf-8">
	<style type="text/css">
                //实现居中
		.content{
			width:200px;
			height:500px;
			margin:10px auto;
		}
	</style>
</head>
<body>
	<div class = "content">
		<img src = "test.jpg" id = "img">
		<div>
		  <input type="button" id = "max" value = "放大">
		  <input type="button" id = "min" value = "减小">
		</div>
	<div>

	<script type="text/javascript">
		window.onload = function(){
			var max = document.getElementById("max");
			max.onclick = function(){
				maxImage();
			}

			var img = document.getElementById("img");
			//var maxWidth = img.width * 1.3;
			//var maxHeight = img.height * 1.3;
  <span style="white-space:pre">			</span>//缩放的最大程度
			var endWidth = img.width * 2;
			var endHeight = img.height * 2;
			var end_minWidth = img.width * 0.3;
			var end_minHeight = img.height * 0.3;
			function maxImage(){
				var maxWidth = img.width * 1.3;
			   	var maxHeight = img.height * 1.3;
				var maxTimer = setInterval(function(){
					
					if(img.width < maxWidth){
						if(img.width < endWidth){
							img.width = img.width * 1.05;
							img.height = img.height * 1.05;
						}else{
							alert("end");
							clearInterval(maxTimer);
						}
					}
					else{
						//alert("end");
						clearInterval(maxTimer);
					}

				},20);
			}

			var min = document.getElementById("min");
			min.onclick = function(){
				minImage();
			}


			function minImage(){
				var minWidth = img.width * 0.7;
				var minHeight = img.height * 0.7;
				var minTimer = setInterval(function(){
					//document.write(img.width);
					//document.write(end_minWidth);
					if(img.width > minWidth){
						if(img.width > end_minWidth){
							img.width = img.width * 0.95;
							img.height = img.height * 0.95;
						}
						else{
							alert("缩小");
							clearInterval(minTimer);
						}

					}
					else{
						clearInterval(minTimer);
					}
				},20);

			}
		}
	</script>
</body>
</html>


parseInt()

position:absolute




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值