按钮单击时缩放图像

时间:2017-04-04 09:03:56

标签: javascript html css

我有一个图像代码,如果你点击它缩小,如果你点击图像框的任何外侧,它会缩放。在那里我可以用一个按钮控制缩放,这样一个按钮可以递增地缩放,另一个按钮会逐渐缩放。这是我的尝试



<!DOCTYPE html>
<html >
<head> 
  <style type="text/css">
    .zoomin img { height: 200px; width: 200px;
    -webkit-transition: all 2s ease;
    -moz-transition: all 2s ease;
    -ms-transition: all 2s ease;
    transition: all 2s ease; }
    .zoomin img:hover { width: 300px; height: 300px; } 
  </style>
</head>
<body>
  <div class="zoomin"> 
     <img src="download.jpg" title="All you need to know about CSS Transitions " /> 
  </div>
</body>
</html> 
<button>plus</button>
<button>minus</button>
&#13;
&#13;
&#13;

有什么更好的方法可以实现

2 个答案:

答案 0 :(得分:1)

只需使用.style.[width/height]更改图像尺寸,css将完成剩下的工作:

function resize(direction) {
  var delta = 100 * direction;

  var element = document.getElementById('img');
  var positionInfo = element.getBoundingClientRect();

  element.style.width = positionInfo.width+delta+'px';
  element.style.height = positionInfo.height+delta+'px';
}
<!DOCTYPE html>
<html >
<head> 
  <style type="text/css">
    .zoomin img { height: 200px; width: 200px;
    -webkit-transition: all 2s ease;
    -moz-transition: all 2s ease;
    -ms-transition: all 2s ease;
    transition: all 2s ease; }
    .zoomin img:hover { width: 300px; height: 300px; } 
  </style>
</head>
<body>
  <div class="zoomin"> 
     <img src="download.jpg" id="img" title="All you need to know about CSS Transitions " /> 
  </div>
</body>
</html> 
<button onClick="resize(1)">plus</button>
<button onClick="resize(-1)">minus</button>

答案 1 :(得分:0)

这很有效,我给每个按钮一个类,一个加号和一个减号,并且有addClass和removeClass。更简单的方法是使用一个按钮并使用toggleClass添加和删除已有的用于zoomin的类。

&#13;
&#13;
$('button.zoomPlus').click(function(){
  $('.zoomin img').addClass('zoomer');
});

$('button.zoomMinus').click(function(){
  $('.zoomin img').removeClass('zoomer');
});
&#13;
.zoomin img { height: 200px; width: 200px;
    -webkit-transition: all 2s ease;
    -moz-transition: all 2s ease;
    -ms-transition: all 2s ease;
    transition: all 2s ease; }
    .zoomin img:hover,
    img.zoomer{ width: 300px; height: 300px; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html >
<head> 
</head>
<body>
  <div class="zoomin"> 
     <img src="http://placehold.it/300x300" title="All you need to know about CSS Transitions " /> 
  </div>
</body>
</html> 
<button class="zoomPlus">plus</button>
<button class="zoomMinus">minus</button>
&#13;
&#13;
&#13;