让jQuery在一行中左右滑动2个对象



我有一个小函数,可以用滑动效果将内容从左边切换到右边。不幸的是,两个div对象(与inline-block)由于它们的大小,在滑动时不会彼此对齐,但其中一个显然总是在另一个的下方。

看到 jsfiddle代码

我试了如下:

  • 设置float:left没有任何帮助
  • div定位为绝对位置,这有助于但也会在从右向左滑动时产生一些意想不到的行为(您自己试试)
  • 延迟/排队动画,工作,但不是真正的用户友好的延迟

我还想提一下,当你想让你的对象都居中时,浮动和不同的定位并不是很有用,所以我更喜欢另一种解决方案。

也许你们有一个想法,我怎么才能使这个平滑,使div对象保持在一条线上?!

做了很多更改,抱歉,但试试这个:

http://jsfiddle.net/jcZ6J/9/

还要注意的是,你不应该把div放在a标签里面。

<div class="content">
  <a href="index.php?show=camp" class="container" data-title="camp"><h2>CAMPS<br />149 &euro;</h2></a>
  <a href="index.php?show=course" class="container" data-title="course"><h2>COURSES<br />49 &euro;</h2></a>
  <div class="slider-viewport">
    <div class="slider-carriage">
        <div id="camp" class="show" title="left"><span>CAMP-INFO</span></div>
        <div id="course" class="show" title="right"><span>COURSES</span></div>
    </div>  
  </div>
</div>

JS

$(function() {
    $('.container').click(function(evt) {
        evt.preventDefault();
        $('.slider-carriage').stop(false, false).animate({
            left: (-100 * $('#' + $(this).data('title')).position().left / $('.slider-viewport').width()) + '%'
        }, 1000);
    });
});

这里有一个小更新,这样调整窗口大小就不成问题了


CSS

@charset "utf-8";
body {
    color: #FFF;
    background-color:#09F;
    font-family: "Arial";
    font-size: 14px;
    margin: 0px;
}
/* CONTENT */
.content {
    width:100%;
    text-align:center;
}
.container {
    text-align: center;
    display: inline-block;
    border: 2px solid #FFF;
    background:rgba(0,0,0,0.5);
    width:180px;
    margin-left:10px;
    margin-right:10px;
    padding-top:20px;
    margin-top:95px;
}
.container:hover {
    border:2px solid #CCC;
    color:#0F0;
}
.slider-viewport {
    position: relative;
    overflow: hidden;
    width: 90%;
    margin: 50px auto;
    height: 20px;
}
.slider-carriage {
    position: absolute;
    width: 200%;
}
.show {
    float: left;
    text-align: center;
    background: #F90;
    width: 50%;
}
.show > span {
    display: block;
    border: 2px solid #FFF;
}

最新更新