gpt4 book ai didi

javascript - 有多少元素在视口(viewport)中可见

转载 作者:可可西里 更新时间:2023-11-01 01:58:08 24 4
gpt4 key购买 nike

页面上有一个div(棕色矩形)。页面高于视口(viewport)(橙色矩形),因此可以滚动,这意味着 div 可能只显示部分或根本不显示。

element visibility

判断 div 有多少百分比在视口(viewport)中可见的最简单算法是什么?

(为了使事情更简单,div 总是水平地适合视口(viewport),所以在计算时只需要考虑 Y 轴。)

最佳答案

请参阅 fiddle 中的另一个示例: https://jsfiddle.net/1hfxom6h/3/

/*jslint browser: true*/
/*global jQuery, window, document*/
(function ($) {
'use strict';
var results = {};

function display() {
var resultString = '';

$.each(results, function (key) {
resultString += '(' + key + ': ' + Math.round(results[key]) + '%)';
});

$('p').text(resultString);
}

function calculateVisibilityForDiv(div$) {
var windowHeight = $(window).height(),
docScroll = $(document).scrollTop(),
divPosition = div$.offset().top,
divHeight = div$.height(),
hiddenBefore = docScroll - divPosition,
hiddenAfter = (divPosition + divHeight) - (docScroll + windowHeight);

if ((docScroll > divPosition + divHeight) || (divPosition > docScroll + windowHeight)) {
return 0;
} else {
var result = 100;

if (hiddenBefore > 0) {
result -= (hiddenBefore * 100) / divHeight;
}

if (hiddenAfter > 0) {
result -= (hiddenAfter * 100) / divHeight;
}

return result;
}
}

function calculateAndDisplayForAllDivs() {
$('div').each(function () {
var div$ = $(this);
results[div$.attr('id')] = calculateVisibilityForDiv(div$);
});

display();
}

$(document).scroll(function () {
calculateAndDisplayForAllDivs();
});

$(document).ready(function () {
calculateAndDisplayForAllDivs();
});
}(jQuery));
div {
height:200px;
width:300px;

border-width:1px;
border-style:solid;
}
p {
position: fixed;
left:320px;
top:4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
<p id="result"></p>

关于javascript - 有多少元素在视口(viewport)中可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33859522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com