最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create a dimmed background on-click - Stack Overflow

programmeradmin2浏览0评论

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 acplish this.

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 acplish this.

Share Improve this question edited Dec 23, 2012 at 19:36 Dutchie432 29.2k20 gold badges93 silver badges109 bronze badges asked Dec 23, 2012 at 19:14 XxDrewJrxXXxDrewJrxX 771 gold badge1 silver badge8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 12

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

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.

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";
}
发布评论

评论列表(0)

  1. 暂无评论