javascript - 是否可以证明 "overflow-x:scroll"div-container 中的可见性 div 元素?

标签 javascript jquery html css

我目前正在尝试弄清楚如何获取 overflow-x:scroll 容器内的 div 可见百分比的信息。我还需要知道它是来自右侧还是来自左侧?这有可能吗?

最佳答案

这可能会有帮助。您可以编辑该问题答案中的代码,以检查元素是从右侧还是左侧滚动的。

Check if element is visible after scrolling

要计算可见百分比,您只需比较子项的大小与父项的大小以及子项的“左”偏移量是多少。

(稍后我可能会添加代码示例)

编辑

我做了一个小例子,展示了如何检测“overflow-x:scroll”div-container 中那个 child 的可见百分比如果 child 来自左边或右边。

<style>
#parent {
    overflow-x:scroll;
    width: 300px;
    height:120px;
    border: solid 1px #000;
}
#child {
    width: 200px;
    height: 100px;
    background:#FF0;
    margin-left: 200px;
}
#scrollPane {
    width: 800px;
}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#button").click(function(){
        alert(percantageVisible() + "% of the child is visible");
    });
});

function percantageVisible()
{
    var parent = $("#parent");
    var parentLeftOffset = parent.offset().left;
    var parentRightOffset = parentLeftOffset + parent.width();

    var child = $("#child");
    var childLeftOffset = child.offset().left;
    var childRightOffset = childLeftOffset + child.width();

    if(childLeftOffset < parentLeftOffset && childRightOffset > parentLeftOffset && childRightOffset < parentRightOffset){
        // percentage from the left
        var width = child.width();
        var hiddenWidth = Math.abs(childLeftOffset - parentLeftOffset);
        var visibleWidth = width - hiddenWidth;
        return visibleWidth/(width/100);
    } 
    else if(childRightOffset > parentRightOffset && childLeftOffset < parentRightOffset && childLeftOffset > parentLeftOffset ){
        // percentage from the right
        var width = child.width();
        var hiddenWidth = Math.abs(parentRightOffset -childRightOffset);
        var visibleWidth = width - hiddenWidth;
        return visibleWidth/(width/100);
    }
    else if (childLeftOffset > parentLeftOffset && childRightOffset < parentRightOffset){
        // all visible
        return 100;
    }
    else{
        // invisible
        return 0;
    }
}
</script>

<div id="parent">
    <div id="scrollPane">
        <div id="child"> </div>
    </div>
</div>
<button id="button">check percentage</button>

希望对你有帮助

关于javascript - 是否可以证明 "overflow-x:scroll"div-container 中的可见性 div 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10994590/

相关文章:

javascript - 无法将 jquery 文件添加到 chrome 扩展

javascript - 如何在 Angular 单元测试中使 Material 组件与 Karma 一起工作

javascript - 如何导入 navigator.notification.alert 插件 PhoneGap

html - 将导航栏完全左对齐并分成 12 个部分

javascript - window.location.replace 不适用于某些网址

javascript - 如何将进度条与 .click 事件 jquery 链接

javascript - 在浏览器选项卡关闭时发送 GET 请求

java - servlet 不会返回到上一页

html - CSS 不用于表 TR 中的 TH 悬停

javascript - 在 JavaScript 中反转和添加