javascript - 强制性虚拟 slider - 动态使用 jQuery

标签 javascript jquery html css animation

我创建了一个带有 2 个按钮(上一个和下一个)的 slider ,允许用户通过前进或后退与图像进行交互。如果在第一张图片和上一张图片处触发,则最后一张图片会向左滑动到 View 中。图像案例的结尾与此相反。

我遇到的问题是动态获取静态图像的宽度。当我使用具有完全相同的选择器和方法的浏览器控制台时,我得到了正确的宽度,但是当我使用 console.log(width) 时,该值为 0,这会导致动画滑动 0px,因此没有交互。

这是我的 JS:

$(document).ready(function () {

//initialize/cache variables needed in program
var sliderUL = $('div.content5').css('overflow', 'hidden').children('ul');          //we can chain variables, for example: we are setting the overflow of an element to hidden, and then we are getting the selected elements of 'ul'.
var imgs = sliderUL.find('img');
var imgWidth = imgs.eq(0).width();           //*SHOULD BE 400, but is 0*
var imgsLen = imgs.length;                  //5
var current = 1;
var totalImgsWidth = imgsLen * imgWidth;   //2000

$('#slider-nav').show().find('button').on('click', function () {

    //direction tells us what button is clicked, previous or next. This is needed for moving forward or backwards
    var direction = $(this).data('dir'),
        loc = imgWidth;     //400, the amount needed to shift to new image, which also is the width of an image

    //update current value
    //if the user clicks on the next button, increase current by 1. else, decrease current by 1, meaning they clicked on the previous button.
    (direction === 'next') ? ++current : --current;
    //if on the first image and the user presses previous, set current equal to the last image
    if (current === 0) {
        current = imgsLen;
        loc = totalImgsWidth - imgWidth;
        //direction next means that it will animate left all the way over to the last image
        direction = 'next';
    } else if (current - 1 === imgsLen) {
        //if the user is on the very last image and they press next, send them back to the first image
        current = 1;
        //send the img location back to 0 pixels, or the first image
        loc = 0;
    }
    transition(sliderUL, loc, direction);
});

//params: 1.what we are animating 2.the location (margin) we're moving to 3.the direction we are moving
function transition(container, loc, direction) {

    var unit;   // -=  OR  +=
    //as long as the user isn't trying to reset, the unit is either going to be equal to -= or +=
    console.log(loc + ' and ' + direction);
    if (direction && loc !== 0) {
        //does direction equal next?
        //if so, increment left sign, else, increment right sign
        if (direction == 'next') {
            unit = '-=';
        } else {
            unit = '+=';
        }
        //            unit = (direction === 'next') ? '-=' : '+=';
    }
    console.log("you are on image: " + current + ", going " + unit);
    container.animate({
        //if unit isn't undefined, animate container. else, reset to 0/first img
        'margin-left': unit ? (direction + loc) : loc    // if true, -=400  OR  +=400   if false, reset back to first image at 0
    });
  }
});

这是我的 HTML:

<div class="content5">
    <h1 class="content5_h1">Content #5 - The Obligatory Slider</h1>
    <ul class="content5_imgs">
        <li><img src="imgs/img1.jpg" alt="/" /></li>
        <li><img src="imgs/img2.jpg" alt="/" /></li>
        <li><img src="imgs/img3.jpg" alt="/" /></li>
        <li><img src="imgs/img4.jpg" alt="/" /></li>
        <li><img src="imgs/img5.jpg" alt="/" /></li>
    </ul>
</div>
<div id="slider-nav">
    <button data-dir="prev">Previous</button>
    <button data-dir="next">Next</button>
</div>

最后,这是我的 CSS:

.content5 {
    width:400px;
    margin:auto;
    height: 368px;
    overflow: scroll;
}

.content5_imgs {
    width:10000px;
    height: 250px;
    list-style: none;
    padding: 0px;
}

.content5_imgs li {
    float:left;
}

#slider-nav {
    display: none;
    margin-top: 1em;
    width:170px;
    margin:auto;
    padding-top: 10px;
}

#slider-nav button {
    padding:1em;
    margin-right: 1em;
    border-radius:10px;
    cursor: pointer;
    background-color: Lime;
}

我尝试链接变量,甚至尝试更改 imgWidth 的选择器,包括 first() 和 [0]。

任何见解都是有帮助的。

最佳答案

如果图像尚未加载,JavaScript 将返回宽度 0。

要解决这个问题,任何依赖于要加载的内容的代码,而不仅仅是准备好 DOM,都需要调用

$(window).load()

代替 $(document).ready()。

更多信息:Official way to ask jQuery wait for all images to load before executing something

关于javascript - 强制性虚拟 slider - 动态使用 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9687614/

相关文章:

javascript - jQuery 用户界面 : Draggable parent outline changes while dragging in firefox

python - 是否有更短的方法或 pythonic 方法来生成遵循使用 BeautifulSoup 模式的自定义 html?

javascript - 当 Accordion 内部有一些点击事件时 Accordion 图标正在改变 : Bootstrap 2. 3 版本

javascript - HTML5 地理定位当前 GPS 位置的纬度和经度坐标放入变量中

javascript,递归地新建对象

javascript - jQuery .on() 和 .delegate() 在 iPad 上不起作用

javascript - 将回调和其他参数传递给 jQuery ajax 是否成功?

javascript - 通过 jQuery 将 H3 标签变成链接?

javascript - bacon.js 中的控制流,如何在给定时间做某事

javascript - 如何获取动态创建的元素宽度并对其应用样式?