gpt4 book ai didi

javascript - 如何测试 "carousel"内的元素(溢出 :hidden"having multiple large children) is visually visible? 的容器)

转载 作者:行者123 更新时间:2023-11-28 10:52:02 26 4
gpt4 key购买 nike

我正在寻找一个通用( native )Javascript 函数,它可以判断元素是否可见,可以考虑“轮播”(又名“ slider ”)中的元素;
这些通常是带有“幻灯片”的容器,每个元素都位于前一个元素的左侧(或右侧) - 但实际上只有一个元素是可见的。
在此网页中可以看到一个示例: http://www.technobuffalo.com/2015/07/22/iphone-7-concept-sports-quad-hd-retina-display-wireless-charging/

编辑:带有 3 张幻灯片的轮播示例:

<div class="carousel">
<div class="slide" style="left:0"><img src="..." /></div>
<div class="slide" style="left:640px"><img src="..." /></div>
<div class="slide" style="left:1280px"><img src="..." /></div>
</div>

<style>
.carousel {
width: 640px;
height: 460px;
overflow: hidden;
}
.slide {
position: absolute;
width: 100%;
height: 100%;
}

</style>

对于轮播中不直接可见的图像,该函数应返回 false

我已经尝试了在有关可见性检测的问题的答案中建议的多种技术,其中包括 - 检查 offsetParentoffsetLeftoffsetRight ,并使用 getCompulatedStyle 并检查 display 等,但对于轮播中不可见的图像,它们都返回 true

最佳答案

使用 boundingClientRect 的简单示例,当 elementLeft ===parentLectelementRight ===parentRight 时,元素可见,具体取决于您的情况

let hash = '#one'
let one = document.getElementById('one')
let two = document.getElementById('two')
let three = document.getElementById('three')

function getResult (el) {
let elementRect = el.getBoundingClientRect()
let parentRect = el.parentElement.getBoundingClientRect()
return `
${el.id} - visible: ${elementRect.left === parentRect.left || elementRect.right === parentRect.right}`
}

function hashChange() {
document.querySelector(`${location.hash || hash} .content`).innerHTML = `
${getResult(one)}<br>
${getResult(two)}<br>
${getResult(three)}<br>
`
}

hashChange()
window.addEventListener('hashchange', hashChange)
.carousel {
display:flex;
height:200px;
width:200px;
overflow-x:hidden;
}

.slide {
display:flex;
flex-direction:column;
flex-shrink:0;
width:100%;
}
<div class="carousel">
<div id="one" class="slide">
<div style="flex:1">
<div>One</div>
<p class="content" />
</div>
<a href="#two">Next</a>
</div>
<div id="two" class="slide">
<div style="flex:1">
<div>Two</div>
<p class="content" />
</div>
<span>
<a href="#one">Previous</a>
<a href="#three">Next</a>
</span>
</div>
<div id="three" class="slide">
<div style="flex:1">
<div>Three</div>
<p class="content" />
</div>
<a href="#two">Previous</a>
</div>
</div>

关于javascript - 如何测试 "carousel"内的元素(溢出 :hidden"having multiple large children) is visually visible? 的容器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31588220/

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