降低高度的问题

时间:2018-06-09 16:32:52

标签: javascript jquery

请你看看这个演示,让我知道为什么我无法降低#map的高度

正如您所看到的,.btn-enlarge正在扩大图像的高度,但.btn-shrink并没有降低高度

$(function() {
  var unit = 10;
  
  $(".btn-enlarge").on("click", function(){
    unit = unit+ unit; 
    $("#map").animate({	
				'height':  $("#map").height()+unit+ 'px'
				});
});
    $(".btn-shrink").on("click", function(){
    unit = unit+ unit; 
    $("#map").animate({	
				'height':  $("#map").height()+'-'+unit+ 'px'
		});
});
});
#map {
  width: 300px;
  height: 300px;
  border: 1px solid rgb(0, 0, 0);
  cursor: move;
  overflow: hidden;
  Background-image: url('https://i.pinimg.com/originals/dd/a5/17/dda5177a3db95a93c0c84ff6847fda23.jpg');
  background-repeat: no-repeat;
    background-size:cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <button type="button" class="btn-shrink">-</button>
  <button type="button" class="btn-enlarge">+</button>
<div id="map"></div>

1 个答案:

答案 0 :(得分:2)

您始终可以使用+=-=

jQuery(function( $ ) {

  var step = 10;

  $(".btn-enlarge, .btn-shrink").on("click", function() {
    var sym = $(this).is(".btn-enlarge") ? "+=" : "-=";
    $("#map").animate({height: sym + step});
  });
  
});
#map {
  width: 300px;
  height: 300px;
  border: 1px solid rgb(0, 0, 0);
  background: url('https://i.stack.imgur.com/O724n.jpg') 50% 50% / contain no-repeat;
}
<button type="button" class="btn-shrink">-</button>
<button type="button" class="btn-enlarge">+</button>
<div id="map"></div>


<script src="//code.jquery.com/jquery-3.1.0.js"></script>

上面的

$("#map").animate({height: sym + step});

转换为:

$("#map").animate({height: "+=10"}); // or
$("#map").animate({height: "-=10"}); // depending on the clicked button