使用布尔值切换

问题描述 投票:1回答:2

我正在尝试设计一个元素。我已经设置了一个布尔值,并使用它来在两个函数之间进行toogle。但是,它不会运行所以我不确定我的脚本是否正确。

var dfault = false

function rand() {
        return~~ (Math.random() * 255);
    }

function get_random_color() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

function randFrame(){
    vid = document.getElementById("video_container");

    if(!dfault){
        vid.style.backgroundColor  = get_random_color();


    }else{
        vid.style.border = ('5px solid rgba(54,57, 62, .3)');

    }

    dfault = !dfault
}

基本上,我喜欢将边框从正常颜色更改为随机颜色然后来回。

HTML:

<div id="sideMenu">
    <ul>
        <li onclick="wideScreen()">Wide Screen</li> <!--turn sidebar on/off-->
        <li onclick="randVidframe()">Random Border</li> <!--randomize vidcontain border-->
        <li>Control Bar</li>
    </ul>
</div>

CSS:

#video_container{
    -webkit-box-flex: 1; 
    -moz-box-flex: 1;
    border:5px solid rgba(54,57, 62, 1);
    margin: 20px;
    /*padding: 5px;*/
    height: 100%;
    position: relative;
    /*background-color:red;*/
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px; 
    z-index: 1;
}
javascript boolean
2个回答
2
投票

你的脚本看起来应该更像这样

var dfault = false

function rand() {
        return~~ (Math.random() * 255);
    }
function randVidframe(){

    if(!dfault){
        elem.style.border = ('5px solid rgb(' + [rand(), rand(), rand()] + ')');

    }else{
        elem.style.border = ('5px solid rgba(54,57, 62, .3)');

    }

    dfault = !dfault
}

1
投票
  1. 每次调用函数时都会重新初始化局部变量 - 您需要使用函数范围之外的变量,但是:
  2. 不要使用全局变量,它们很糟糕 - 好吗?
  3. 确保在DOM准备好之前不会调用您的脚本。如果您过早运行它,那么您的元素将无法用于您的脚本。

即:

// don't do anything until the DOM is ready
window.onload = function() {

    // local variables
    var dfault;
    var elem = document.getElementById('myelem');

    // local function, not global
    function rand() {
        return ~~(Math.random() * 255);
    }

    // despite above warning, this function has to be global
    // because you're using DOM level 0 inline event handlers :(
    window.randVidframe = function() {
        dfault = !dfault;

        if (dfault) {  // put "true" test first
            elem.style.border = ('5px solid rgba(54,57, 62, .3)');
        } else {
            elem.style.border = ('5px solid rgb(' + [rand(), rand(), rand()] + ')');
        }
    };

    window.wideScreen = function() {
        ...
    };
}; 
© www.soinside.com 2019 - 2024. All rights reserved.