javascript 单击创建一个变暗的背景
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14013924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a dimmed background on-click
提问by XxDrewJrxX
Hopefully not too vague. All I want to do is make the entire page go dim after clicking a link. I would imagine having div style="height:100%; width=100%;"
with a high z-index
. to cover the webpage. My question is toggling this div. I'm not sure what I should even use to accomplish this.
希望不要太含糊。我想要做的就是在单击链接后使整个页面变暗。我会想象有div style="height:100%; width=100%;"
一个高z-index
。覆盖网页。我的问题是切换这个 div。我不确定我什至应该用什么来完成这个。
回答by Popnoodles
Demos using jQueryor using bog-standard Javascript, both showing how you can toggle the element.
使用 jQuery或使用 bog-standard Javascript 的演示,都展示了如何切换元素。
HTMLYou didn't say how you want to toggle this. Using a button?
HTML你没有说你想如何切换它。使用按钮?
<button onclick="dim();">Dim</button>
<div id="dimmer"></div>
but bear in mind the dimmer will go over the button
但请记住,调光器会超过按钮
CSS
CSS
#dimmer
{
background:#000;
opacity:0.5;
position:fixed; /* important to use fixed, not absolute */
top:0;
left:0;
width:100%;
height:100%;
display:none;
z-index:9999; /* may not be necessary */
}
N.B. Use position: fixed
as 100% height is only the window height and if your document is larger, using position: absolute
doesn't dim the whole document - you can scroll to see there are contents visible.
注意使用position: fixed
100% 高度只是窗口高度,如果您的文档较大,则使用position: absolute
不会使整个文档变暗 - 您可以滚动查看是否有可见的内容。
Javascript
Javascript
function dim(bool)
{
if (typeof bool=='undefined') bool=true; // so you can shorten dim(true) to dim()
document.getElementById('dimmer').style.display=(bool?'block':'none');
}
dim(true); // on
dim(false); // off
回答by Mr. Alien
You can do it with a simple JavaScript
你可以用一个简单的 JavaScript 来完成
HTML
HTML
<a href="#" onclick="dim_div()">Click me</a>
<div id="toggle_div"></div>
Hello World
JavaScript
JavaScript
function dim_div() {
document.getElementById("toggle_div").style.display="block";
}
CSS
CSS
#toggle_div {
background-color: rgba(255, 255, 255, .6);
display: none;
position: absolute;
width: 100%;
height: 100%;
top: 0;
z-index: 999;
}
回答by user3405291
HTML
HTML
<div id="initial_opacity_zero"></div>
<button id="button_to_adjust_opacity" onclick="func_onclick();"></button>
CSS
CSS
div#initial_opacity_zero{
opacity:0;
display:block;
position:fixed;
top:0px; right:0px; bottom:0px; left:0px;
}
JavaScript:
JavaScript:
function func_onclick(){
document.getElementById("initial_opacity_zero").style.opacity="0.6";
}