【问题标题】:Set percentage value to scrollLeft() in jQuery在 jQuery 中将百分比值设置为 scrollLeft()
【发布时间】:2015-10-14 10:00:07
【问题描述】:

这有点令人困惑(我认为这是不可能的)。我找到了如何从Blazemonger's answer on SO获取滚动量百分比:

scrollPercentage = 100 * $(this).scrollLeft() / ($('#contained').width() - $(this).width());

好的,这个解决方案很好用,但是我的问题是如何使用 jQuery 设置滚动量?

我同时滚动两个可滚动的 div,我尝试了这个:

$(".mycontainer").scroll(function(){    
    var scrollPercentage = 100 * $(this).scrollLeft() / ($(".mycontainerContent").width() - $(this).width())
        $(".anotherContainer").scrollLeft(scrollPercentage);
});

但该代码不起作用。

我尝试添加百分比符号,但结果相同 - 没有任何反应。

$(".mycontainer").scroll(function(){    
    var scrollPercentage = 100 * $(this).scrollLeft() / ($(".mycontainerContent").width() - $(this).width())
        $(".anotherContainer").scrollLeft(scrollPercentage.toFixed(0)+'%');
});

有什么想法吗?

编辑 - jgasiorowski's answer 有点工作:

您需要再次将百分比值更改为原始类型以进行滚动

 var scrollValueForAnother = ($(".anotherContainer").width() -
 $(this).width()) * (percentage / 100);
 $(".anotherContainer").scrollLeft(scrollValueForAnother);

希望我没有计算错误

但就像我在他的回答的评论中提到的那样:

它有点工作,但 $(".anotherContainer") 之前到达结束 $(".myContainer") 到达终点。我想同步两个可滚动区域 同时到达卷轴的尽头。我希望我能 解释一下。

*两个可滚动区域的宽度不同!

【问题讨论】:

    标签: javascript jquery scroll scrollbar percentage


    【解决方案1】:

    您需要再次将百分比值更改为原始类型以进行滚动

    var scrollValueForAnother = ($(".anotherContainer").width() - $(this).width()) * (percentage / 100);
    $(".anotherContainer").scrollLeft(scrollValueForAnother);
    

    希望我没有计算错误

    EDIT2:我做了那个小小提琴https://jsfiddle.net/b4d9bLnm/1/ 所以你的代码应该是这样的:

    $(".mycontainer").scroll(function(){  
        var container2 = $(".anotherContainer");  
        var scrollPercentage = 100 * $(this).scrollLeft() / (this.scrollWidth - this.clientWidth);
    
        var scrollValueForAnother = (container2[0].scrollWidth -  container2[0].clientWidth) * (percentage / 100);
        $(".anotherContainer").scrollLeft(scrollValueForAnother);
    });
    

    【讨论】:

    • 它有点工作,但 $(".anotherContainer") 在 $(".myContainer") 到达终点之前到达终点。我想同步两个可滚动区域以同时到达滚动结束。我希望我能解释一下。
    • @CeylanMumunKocabaş 我已经更新了我的帖子 - 也许现在它会更有帮助
    • 非常感谢,我会批准你的回答,但我还有一个小愿望,因为我的数学太差了——你能不能让容器 1 比容器 2 更宽。我试着做但失败了:(实际上我需要更宽的容器来引导小容器滚动
    • 伙计,我的情况要复杂得多,我的从属可滚动容器内容是旋转和动态的......我迷路了:D 不管,你是魔术师 \\// 坦克
    • @CeylanMumunKocabaş 再次更新 - 现在计算应该是完美的:)
    猜你喜欢
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 2016-10-20
    • 2010-10-17
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    相关资源
    最近更新 更多