0

我正在使用引导轮播并希望将其修改为始终适合窗口(或任何其他设备)的滑块。这是我的解决方案:

如果imageRatio > winRatio那么
stretch images height to it's max
否则
stretch images width to it's max

当图像比例大于窗口比例时,我添加max-height:100%;max-width:none;到图像中,当窗口比例大于图像比例时,我添加max-width: 100%; max-height: none;

长话短说,所有这些东西都有效,但是当我调整窗口图像比例和窗口比例时不知何故!这是`console.log(winRatio,imgRatio)的结果;

1.0709046454767726 1.5051546391752577 /* this is expected results but */
1.1124694376528117 1.1124694376528117 /* when i stop resizing */

我的 HTML:

<div class="row-fluid">

    <div id="top-slider" class="carousel slide">
        <!-- Carousel pattern mask -->
        <div class="mask"></div>

        <!-- Carousel items -->
        <div class="carousel-inner">
            <div class="active item"><img src="img/slider/slide01.jpg" alt="Slide 01" /></div>
            <div class="item"><img src="img/slider/slide02.jpg" alt="Slide 02" /></div>
            <div class="item"><img src="img/slider/slide03.jpg" alt="Slide 03" /></div>
        </div>

        <!-- Carousel nav -->
        <div class="carousel-control">
            <a class="left" href="#top-slider" data-slide="prev"></a>
            <a class="right" href="#top-slider" data-slide="next"></a>
        </div>
    </div>

</div>
<!-- /site top slider -->

Javascript:

// DOM Ready
jQuery(document).ready(function($){

    /* strech homepage top slider's slides to fit device screen
    ------------------------------------------------------------------- */
    function fitSlider() {
        var wH = $(window).height() - $('#top-header').height();
        var wW = $(window).width();
        var winRatio = wW / wH;
        var imgH = $('#top-slider .carousel-inner').height();
        var imgW = $('#top-slider .carousel-inner').width();
        var imgRatio = imgW / imgH;
        console.log(winRatio, imgRatio);

        $('#top-slider').css('height', wH);

        if ( imgRatio > winRatio )
        {
            $('#top-slider .carousel-inner .item img').addClass('fit-height');
        }
        else
        {
            $('#top-slider .carousel-inner .item img').removeClass('fit-height');
        }
    }

    // On window resized fire this event
    $(window).bind('resize',function() {
        //Update slider
        fitSlider();
    });
    // On window loaded fire this event
    $(window).load(function() {
        fitSlider();
    });
});
4

1 回答 1

1

第一次运行脚本时,图像的大小会发生变化。所以下次你获取它时,你会得到你设置的图像的大小,而不是原始的初始高度。您必须将图像的初始尺寸存储在某个全局变量中,并将窗口尺寸与它们进行比较。

将这些转移到 window.load 函数中。并使这些变量全局化。

var imgH = $('#top-slider .carousel-inner').height();
var imgW = $('#top-slider .carousel-inner').width();
于 2013-03-28T08:59:28.290 回答