JavaScript 如何使整个屏幕变暗,除了一个固定区域
给定一个HTML文档,任务是将整个屏幕变暗,除了一个或几个元素。这需要使用JavaScript来引起用户对页面的某个部分的注意。
方法:
- 选择要聚焦的元素。
- 使用 box-shadow属性 使该区域可见。
示例1: 此示例将焦点放在HTML文档的一个div上,另一部分变暗。
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to Dim entire screen except a
fixed area using JavaScript ?
</title>
<style>
.dim {
/* For Internet Explorer */
box-shadow: 0 0 0 1000px rgba(0, 0, 0, .3);
/* For other browsers */
box-shadow: 0 0 0 100vmax rgba(0, 0, 0, .3);
}
</style>
</head>
<body>
<h1 style="color:green;" id="h1">
GeeksforGeeks
</h1>
<h3>
Click on button to make everything
dim on the screen.
</h3>
<button onclick="GFG_Fun()">
click here
</button>
<h3 id="GFG" style="color:green;">
</h3>
<script>
let elm = document.getElementById('GFG');
let heading = document.getElementById('h1');
function GFG_Fun() {
heading.classList.add('dim');
elm.innerHTML = "Everything becomes dim "
+ "except heading(h1)";
}
</script>
</body>
</html>
输出:
示例2: 在这个示例中,按钮获得焦点,同时 pointer-events 属性设置为none,并且另一部分被变暗。
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to Dim entire screen except a
fixed area using JavaScript ?
</title>
<style>
.dim {
/* For Internet Explorer */
box-shadow: 0 0 0 1000px rgba(0, 0, 0, .3);
/* For other browsers */
box-shadow: 0 0 0 100vmax rgba(0, 0, 0, .3);
pointer-events: none;
}
</style>
</head>
<body>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
Click on button to make everything
dim on the screen.
</h3>
<button onclick="GFG_Fun()" id="button">
click here
</button>
<h3 id="GFG" style="color:green;">
</h3>
<script>
let elm = document.getElementById('GFG');
let btn = document.getElementById('button');
function GFG_Fun() {
btn.classList.add('dim');
elm.innerHTML = "Everything becomes dim"
+ " except button";
}
</script>
</body>
</html>
输出: