如何修复Bootstrap Carousel' offSetWidth'错误

时间:2016-05-19 06:23:58

标签: javascript twitter-bootstrap carousel

我用Bootstrap创建了一个旋转木马然后我收到了这个错误:Uncaught TypeError: Cannot read property 'offsetWidth' of undefined.导致错误我无法滑动我的旋转木马控件。

这是我的HTML:



<div id="carousel-example-generic" class="carousel slide center" data-ride="carousel" >
   <div class="carousel-inner center" role="listbox" style="width:500px;height: 500px;margin: auto" ></div>
     <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
        <span class="sr-only">Previous</span></a>
     <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
        <span class="sr-only">Next</span>
     </a>
</div>
&#13;
&#13;
&#13;

这是我的JavaScript:

&#13;
&#13;
$('a.certPhoto').click(function () {
        $('#photoDialog').modal('show');
        var _a = $(this).parents("tr");
        $("#photoDialog span.p_name").text(_a.find('.real_name').text());
        $("#photoDialog span.p_type").text(_a.find('.cert_type').text());
        $("#photoDialog span.p_ID").text(_a.find('.cert').text());
        var photo = $(this).data('photo');
        var _html = "";
        for (var i = 0, len = photo.length; i < len; i++) {
            if (i == 0) {
                _html += '<div class="item active"> <img src="' + photo[i] + '" alt=""  ><div class="carousel-caption"> </div></div>';
            } else {
                _html += '<div class="item"> <img src="' + photo[i] + '" alt=""><div class="carousel-caption"> </div></div>';
            }
        }
        $('.carousel-inner').html(_html);
        $(".carousel-inner img").each(function (i) {
            var img = $(this);
            var realWidth;
            var realHeight;
            $("<img/>").attr("src", $(img).attr("src")).load(function () {
                realWidth = this.width;
                realHeight = this.height;
                if (realWidth >= realHeight) {
                    if (realWidth > 500) {
                        $(img).css("width", "500px");
                    }
                } else {
                    if (realHeight > 500) {
                        var _left = 500 * (1 - realWidth / realHeight) / 2;
                        $(img).css("height", '500px').css('margin-left', _left + "px");
                    }
                }
            });
        });

    });
&#13;
&#13;
&#13;

我发现了一些类似的问题,但它们似乎并不适用于我。导致类似问题的原因主要是缺乏课程“活跃”。但我不是。这个错误是偶然发生的,这很奇怪。当我刷新窗口时,这个错误就会被修复。

任何建议都会很棒。谢谢!

1 个答案:

答案 0 :(得分:1)

这是因为.carousel-inner中没有元素item开头。添加一些.item后,您需要调用$('.carousel').carousel()来初始化轮播。

以下是Bootstrap轮播文档的link