简体   繁体   中英

Create a dimmed background on-click

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.

Demos using jQuery or using bog-standard Javascript , both showing how you can toggle the element.

HTML You didn't say how you want to toggle this. Using a button?

<button onclick="dim();">Dim</button>
<div id="dimmer"></div> 

but bear in mind the dimmer will go over the button

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 */
}

NB 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.

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

You can do it with a simple JavaScript

Demo

HTML

<a href="#" onclick="dim_div()">Click me</a>
<div id="toggle_div"></div>
Hello World

JavaScript

function dim_div() {
    document.getElementById("toggle_div").style.display="block";
}

CSS

#toggle_div {
    background-color: rgba(255, 255, 255, .6);
    display: none;
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    z-index: 999;
}

HTML

<div id="initial_opacity_zero"></div>
<button id="button_to_adjust_opacity" onclick="func_onclick();"></button>

CSS

div#initial_opacity_zero{
  opacity:0;
  display:block;
  position:fixed;
  top:0px; right:0px; bottom:0px; left:0px;
}

JavaScript:

function func_onclick(){
  document.getElementById("initial_opacity_zero").style.opacity="0.6";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM