我如何调整这个JavaScript工作和响应?

时间:2013-11-23 18:31:14

标签: javascript jquery html css

我希望将100%作为图片的宽度而不是特定的px编号,但它会在没有特定尺寸的情况下断开。

这是一种调整JavaScript的方法,所以我可以响应性地进行这项工作吗?

的Javascript

$(document).ready(function(){
    var $after = $('.after'),
        img_width = $('.after img').width(),
        init_split = Math.round(img_width/2);

      $after.width(init_split);  

        $('.before_after_slider').mousemove(function(e){
        var offX  = (e.offsetX || e.clientX - $after.offset().left);
            $after.width(offX);
        });

        $('.before_after_slider').mouseleave(function(e){
        $after.stop().animate({
        width: init_split
        },1000)
        });
});

HTML

<div class="before_after_slider">
  <div class="before">
    <img src="center_before.jpg" width="auto" height="600px" alt="before" />
  </div>
  <div class="after">
    <img src="center_after.jpg" width="100%" height="600px"  alt="after" />
  </div>
</div>

2 个答案:

答案 0 :(得分:0)

您是否考虑过使用css进行此操作?

.before { 
  background: url(center_before.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

答案 1 :(得分:0)

我能够使这个脚本响应如下......

$(document).ready(function() {
  var $parent = $('.before_after_slider');
  var $after = $('.before_after_slider .after');
  var $image = $('.before_after_slider .after img');

  var img_width = $('.before_after_slider .after img').width();
  var img_height = $('.before_after_slider .after img').height();

  var init_split = Math.round(img_width/2);

  // Calculate responsive width correctly (after image is loaded).
  $('.before_after_slider .after img').load(function(){
    var img_height = $(this).height();
    img_width = $(this).width();
    img_height = $(this).height();
    init_split = Math.round(img_width/2);
  });

  // Set the height of the parent to prevent collapse.
  $parent.height(img_height);

  // Set the image height and width to 100% (now fixed).
  $image.height(img_height);
  $image.width(img_width);

  // Set the container height to 100% but the width to 50%.
  $after.height(img_height);
  $after.width(init_split);

  // Adjust container width based on mouse movement.
  $('.before_after_slider').mousemove(function(e) {
    var offX  = (e.offsetX || e.clientX - $after.offset().left);
    $after.width(offX);
  });

  // Reset container to 50% when mouse leaves area.
  $('.before_after_slider').mouseleave(function(e) {
    $after.stop().animate({
      width: init_split
    },1000)
  });

});