点击时,jQuery使div增加200%

时间:2016-02-11 09:23:58

标签: jquery

我有一个欢迎div,点击链接里面我希望扩展一倍。我的问题是,开始时的宽度是持有div的百分比,所以100%,我想让链接上的div点击动画扩展到200%,然后如果点击链接再次动画回来,这里是我有的:

var enlarged = false;

$('.welcome a.expand').click(function(e) {
    e.preventDefault();
    $('.welcome').stop(true, false).animate({
        width: enlarged ? 100 : 200,  // Original width is 100%
        height: enlarged ? 355 : 455, // Original height is 355px
    }, 200);

    enlarged = !enlarged;
});

据我所知,jQuery使用的是基于px的数字,因此宽度设置中的100和200我需要基于%。

我还有其他段落的文字,我希望在div扩展后显示这样的延迟,然后当然我需要在关闭时首先删除段落并且延迟将div返回到正常宽度和身高。

请有人指出我正确的方向。

非常感谢

3 个答案:

答案 0 :(得分:6)

如果我是你,我会使用CSS。

$(function(){
    $("div").click(function(){$(this).toggleClass("active")})
})
div {
  width:100px;
  height:100px;
  background: #a00;
  margin:100px;
  transition: all 1s ease-out;
}

div.active {
  transform: scale(2,2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>asd</div>

所以OP上有评论不想放大内容,这里是另一个片段。

$(function(){
    $("div").click(function(){$(this).toggleClass("active")})
})
div {
  width:100px;
  height:100px;
  background: #a00;
  margin:100px;
  transition: all 1s ease-out;
}

div.active {
  width:200px;
  height:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>asd</div>

如果您想支持旧浏览器(即IE 10 - )

$(function(){
    $("div").click(function(){
        var targetw = 100;
        var targeth = 100;
        $(this).toggleClass("active");
        if ($(this).hasClass("active")) {
          targetw *= 2;
          targeth *= 2;
        }
        $(this).animate({width:targetw, height:targeth});
    })
})
div {
  width:100px;
  height:100px;
  background: #a00;
  margin:100px;
  transition: all 1s ease-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>asd</div>

答案 1 :(得分:4)

这是jQuery的解决方案,它不依赖于硬编码的高度和宽度值:

var enlarged = false;

$('.enlarge').on('click', function() {
  var width = $(this).width();
  var height = $(this).height();
  var $p = $(this).find('p')

  if (!enlarged) {
    width = width * 2;
    height = height * 2;
    enlarged = true;
    var callback = function($this) {
      $this.show();
    };
  } else {
    width = width / 2;
    height = height / 2;
    enlarged = false;
    var callback = function($this) {
      $this.hide();
    };
  }

  $(this).stop().animate({
    width: width,
    height: height
  }, callback($p));

});

我正在向animate()添加一个回调函数,以显示或隐藏div中的段落。

<强> Demo

答案 2 :(得分:1)

使用CSS尝试相同

我在这里添加小提琴: https://jsfiddle.net/nexus5786/5L0yvqda/

<强> JQUERY:

$(".but").click(function(){
    $(".test").toggleClass("large");

});

由于

相关问题