保持元素以滑块为中心(跟随时)

时间:2014-01-13 09:24:56

标签: javascript jquery css

是的,所以我有一个问题来帮助解决这个问题的第一部分,这只是让div跟随滑块旋钮。在搞乱了一段时间后,我们提出了解决方案。现在我有一个div跟随滑块旋钮,我需要它始终居中。

所以尽量保持这个简单,这是我想要修复的图像。

Image

在上图中,您可以看到滑块和滑块旋钮后面的div。在那之下我有|的位置,所以你可以看到它没有完全以滑块旋钮为中心。我需要它始终在滑块旋钮下居中(在图像中它应该位于灰色位的中间/中间)。当40%及以下以及60%及以上时,它往往会开始变得混乱。

我尝试了什么:

我无法想出一个简单的方法来解决这个问题(因此这篇文章),但我做了以下尝试做了一点作弊:

if (pct >= 80) {
    // Position the follow div and arrow
    $('#follow').css('left', (o.value * 0.98) + '%');
} else if (pct >= 70) {
    $('#follow').css('left', (o.value * 0.99) + '%');
} else if (pct <= 50 & pct >= 40) {
    $('#follow').css('left', (o.value * 1.02) + '%');
} else if (pct <= 40 & pct >= 30) {
    $('#follow').css('left', (o.value * 1.04) + '%');
} else if (pct <= 30 & pct >= 20) {
    $('#follow').css('left', (o.value * 1.08) + '%');
}

现在,通过在移动时更改div,可以使%与滑块保持一致。这确实有效(有点),但导致div不平滑,并且由于计算更正而导致全部跳跃。

以下是我目前的例子:

HTML:

<div class="slider-container">
    <div id="follow-container">
        <div id="follow">I am following the slider!
            <br />
            <div id="percentage"></div>
            <br />|</div>
    </div>
    <div id="testslider"></div>
</div>

CSS:

#testslider {
    position: absolute;
    top: 50px;
    left: -40px;
    background-size: 100%;
    background-position: center;
}
.slider-container {
    padding: 55px;
}
#follow-container {
    position: relative;
    left: -65px;
    bottom: 2px;
}
#follow {
    position: absolute;
    width: 193px;
    height:40px;
    margin-left: -77px;
    /* half width */
    text-align: center;
    color: black;
    border: 1px solid;
}

JAVASCRIPT:

$('#testslider').sGlide({
    height: 16,
    startAt: 70,
    colorStart: '#C6F1F8',
    colorEnd: '#C6F1F8',
    drag: function (o) {
        var pct = Math.round((o.value));
        $('#percentage').html(pct);

        // Position the follow div and arrow
        $('#follow').css('left', o.value + '%');

    },
    onButton: function (o) {
        var pct = Math.round(o.value) + '%';
        $('#percentage').html(pct);
    }
});

DEMO HERE

这里的任何帮助都会很棒,因为之前有人说过#34;那么你的问题是什么?#/ p>

总体问题:如何让以下div与滑块旋钮保持一致?

2 个答案:

答案 0 :(得分:1)

我能看到它工作的唯一方法是将|包裹在span类中!!

working fiddle

<强> HTML

<span class="vline"><br />|</span>

<强> CSS

#follow > span.vline {
    position: relative;
    left:4%;
}

修改

根据评论讨论,这可能是你的宝贝!!

solution 基于你的问题小提琴,而不是我的第一次尝试小提琴

<强> CSS

 #follow-container {
        position: fixed; /*changed*/
        left:50%; /* change as per your need, left:60%; would make it 
 center to the full 100% width*/
        margin-left:-96px; /*half of divs width*/
    }

答案 1 :(得分:1)

毕竟这一切都解决了我的问题,我需要给#follow-container一个宽度。

使用滑块正确使用允许子div与滑块旋钮正确对齐。

示例:

#follow-container {
    position: relative;
    bottom: 2px;
    width: 760px;
    left: -100px;
}

这似乎解决了我在我的真实项目中的问题,感谢所有帮助NoobEditorMr.Alien