簡體   English   中英

如何調整此javascript以使其正常工作並做出響應?

[英]how do i adjust this javascript to work and be responsive?

我希望圖像的寬度為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>

您是否考慮過使用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;
}

我能夠使該腳本響應如下:

$(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)
  });

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM