怎么判断两个平行的dom是否包含?

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<style type="text/css">

* {

padding: 0;

margin: 0;

}

html, body {

height: 100vh;

}

.container {

position: relative;

height: 100vh;

}

.wrap {

position: relative;

width: 1200px;

height: 600px;

}

.mark {

position: absolute;

width: 400px;

height: 400px;

background: gold;

opacity: 0.3;

left: 0px;

top: 0;

}

.wrap-item {

position: absolute;

}

.item1 {

width: 100px;

height: 50px;

background-color: darkred;

top: 10px;

left: 20px;

}

.item2 {

width: 50px;

height: 100px;

background-color: blue;

top: 200px;

left: 20px;

}

.item3 {

width: 150px;

height: 100px;

background-color: #0ab8d3;

top: 200px;

left: 300px;

}

</style>

</head>

<body>

<div class="container">

<div class="wrap">

<div class="wrap-item item1">

item1

</div>

<div class="wrap-item item2">

item2

</div>

<div class="wrap-item item3">

item3

</div>

</div>

<div class="mark"></div>

</div>

</body>

</html>

怎么判断两个平行的dom是否包含?
从上图中可以看出黄色背景mark包含了item1, item2但是不包含item3,请问应该怎么判断


回答:

function isContained(element, container) {

const containerRect = container.getBoundingClientRect();

const elementRect = element.getBoundingClientRect();

return (

elementRect.top >= containerRect.top &&

elementRect.left >= containerRect.left &&

elementRect.bottom <= containerRect.bottom &&

elementRect.right <= containerRect.right

);

}

const mark = document.querySelector(".mark");

const item1 = document.querySelector(".item1");

const item2 = document.querySelector(".item2");

const item3 = document.querySelector(".item3");

console.log("Item 1 is contained:", isContained(item1, mark));

console.log("Item 2 is contained:", isContained(item2, mark));

console.log("Item 3 is contained:", isContained(item3, mark));

以上是 怎么判断两个平行的dom是否包含? 的全部内容, 来源链接: utcz.com/p/934233.html

回到顶部