如何将img维度从html移动到css并保持此滑块工作

how can i move the img dimensions from html to css and keep this slider working?

本文关键字:css 工作 移动 img html      更新时间:2024-04-20

我有这个前后滑块(第一个内联图像)http://whitewashed.richiesiegel.com/我想将图像维度属性移到css中,但这样做会中断。知道怎么解决吗?

js小提琴在这里http://jsfiddle.net/85jtY/

HTML

<div class="before_after_slider">
    <div class="photo">
    <div class="after">
    <img src="http://whitewashed.richiesiegel.com/images/cans.jpg" width="1000px" height="600px"  alt="after" />
    </div>
    <div class="before">
    <img src="http://whitewashed.richiesiegel.com/center_after.jpg" width="1000px" height="600px" alt="before" />
    </div>
    </div>
    </div>
    <div class="caption">
    <p>Roll over the photo with your cursor to see the before/after images. </p>
  </div>

CSS

.before_after_slider {
    position: relative;
    padding-bottom: 10px;
    width:1000px;
    margin: 0 auto;
  & > * {
    position: relative;
  }
}
.after {
  overflow: hidden;
  position: absolute;
  top: 0px;
  width:1000px;
  height:600px;
}
.caption {
    font-family: helvetica;
    font-weight: 100;
    line-height: 140%;
    letter-spacing: 0px;
    font-size: 13px;
    width:1000px;
    margin: 0 auto;
    padding-top: 0px;
    padding-bottom: 30px;
}

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
        },200)
        });
});

fiddle

.pic{
  width:100%;
  height:100%;
 }

将类添加到img属性

您的javascript的这一行。。。

img_width = $('.after img').width()

正在获取img元素的宽度,但css中没有设置img元素的宽度而是仅设置包装div元素的img元素。所以你需要显式地设置宽度,比如…

.before img,
.after img {
   width: 1000px;
   height: 600px;
}

或者(类似于Sai Ram Sudheer的答案,但没有添加额外的类别),就像这样…

.before img,
.after img {
   width: 100%;
   height: 100%;
}

其利用包装器div维度来确定图像的大小。关键是,您必须实际给img本身一个大小,而不仅仅是img的包装器,$('.after img').width()函数调用才能工作。然后,您应该能够消除html中的设置。