简体   繁体   English

单击主 div 时更改整个页面的背景颜色

[英]Change background color of whole page on click at main div

I try to change the background color of my whole page, on click on my div with id main .我尝试更改我整个页面的背景颜色,点击我的 div 和 id main Here is my code :这是我的代码

 $(document).ready(function() { var color = 1; $('#main').click(function(){ if (color == 1) { $(this).css("background-color", "green"); color = 2; } else if (color == 2) { $(this).css("background-color", "black"); color = 1; } }); });
 #admin_div { position: absolute; width: 80%; height: 80%; border: 2px solid white; border-radius: 10px; background-color: #D9D9D9; z-index: 1; } h1 { margin-left: 15px; } #main { height: 100%; width: 100%; z-index: 0; }
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> <div id="main"> <div id="admin_div"> <h1>Admin Panel</h1> </div> </div>

But the background color is also changing if i click on another element than main.但是,如果我单击 main 之外的另一个元素,背景颜色也会发生变化。 I think it is because everything is inside the main div.我认为这是因为一切都在主 div 内。

Clicking on red color (target div) everything work like exprected单击红色(目标 div)一切正常

http://jsfiddle.net/22m0to5o/1/ http://jsfiddle.net/22m0to5o/1/

var color = 1;

$('#main').click(function (event) {

    if (event.target !== this) return;

    if (color == 1) 
    {
        $('body').css("background-color", "green");
        color = 2;
    } 
    if (color == 2) 
    {
        $('body').css("background-color", "black");
        color = 1;
    }

});

This is a kind of useless piece of JavaScript code, although I suppose it could be useful for something.这是一段无用的 JavaScript 代码,尽管我认为它可能对某些事情有用。 Whether this is just a waste of time or not, I will present you with the code straightaway, that will allow you to dynamically change the background color of the page.无论这是否只是浪费时间,我都会直接向您展示代码,这将允许您动态更改页面的背景颜色。

<script language="JavaScript">
<!--
function changeBGC(color){
document.bgColor = color;
}
//-->
</script>

I think it is quite simple.我认为这很简单。

if you want to change the background color of the whole page, just rewrite the jquery code.如果你想改变整个页面的背景颜色,只需重写jquery代码即可。 change $(this) to $('body').将 $(this) 更改为 $('body')。

 <script>
$(document).ready
(
    function()
    {
        var color = 1;

        $('#main').click
        (
            function()
            {
                if (color == 1)
                {
                    $('body').css("background-color", "green");
                    color = 2;
                } 
                else if (color == 2)
                {
                    $('body').css("background-color", "black");
                    color = 1;  
                }

            }
        );

    }
);
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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