使用计时器实现图片的准确缩放

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自制缩放</title>
    <style>
        #wrapper{
            width: 500px;
            margin: 0 auto;
            position: relative;
        }
        #input{
            position: absolute;
            top: 0px;
        }
        input{
            color:green;
            background: white;
        }
    </style>
</head>
<body>
    <div id="wrapper">
        <div id="input">
            <input  type="button" value="放大" id="enlarge"><input type="button" value="缩小" id="narrow">
        </div>
        <img src="4.jpg" alt="this is a picture" id="myImage">
    </div>
    <script>
    window.onload=function(){
        var image=document.getElementById("myImage");
        var largeButton=document.getElementById("enlarge");
        largeButton.onclick=function(){
            larger();
        }
        var maxWidth=image.width*2.5;
        var maxHeight=image.height*2.5;
        function larger(){
            var endHeight=image.height*1.3;
            var endWidth=image.width*1.3;
            var largeTimer=setInterval(function(){
                if(image.width<endWidth){
                    if(image.width<maxWidth){
                        image.width=image.width*1.03;
                        image.height=image.height*1.03;
                    }else{
                        alert("此图片已经放到了最大。");
                        clearInterval(largeTimer);
                    }
                }else{
                    clearInterval(largeTimer);
                }
            },80);
        }
        var smallButton=document.getElementById("narrow");
        smallButton.onclick=function(){
            smaller();
        }
        var minWidth=image.width*0.5;
        var minHeight=image.height*0.5;
        function smaller(){
            var endWidth=image.width*0.7;
            var endHeight=image.height*0.7;
            var smallTimer=setInterval(function(){
                if(image.width>endWidth){
                    if(image.width>minWidth){
                        image.width=image.width*0.95;
                        image.height=image.height*0.95;
                    }else{
                        alert("此图片已经缩到了最小");
                        clearInterval(smallTimer);
                    }
                }else{
                    clearInterval(smallTimer);
                }
            },130);
        }
    }
    </script>
</body>
</html>
posted @ 2017-08-11 11:36  张松任  阅读(135)  评论(0编辑  收藏  举报
友情链接:上海回力 | 中老年高档女装